How do I initialize the vector I have defined in my header file?
I have the following in my Puzzle.h
class Puzzle
{
private:
vector<int> puzzle;
public:
Puzzle() : puzzle (16) {}
bool isSolved();
void shuffle(vector<int>& );
};
and then my Puzzle.cpp looks like:
Puzzle::Puzzle()
{
// Initialize the puzzle (0,1,2,3,...,14,15)
for(int i = 0; i <= puzzle.size(); i++)
{
puzzle[i] = i;
}
}
// ... other methods
Am I using the initializer list wrong in my header file? I would like to define a vector of ints and initialize its size to that of 16. How should I do this?
G++ Output:
Puzzle.cpp:16: error: expected unqualified-id before ')' token
Puzzle.cpp: In constructor `Puzzle::Puzzle()':
Puzzle.cpp:16: error: expected `)' at end of input
Puzzle.cpp:16: error: expected `{' at end of input
Puzzle.cpp: At global scope:
Puzzle.cpp:24: error: redefinition开发者_如何学运维 of `Puzzle::Puzzle()'
Puzzle.cpp:16: error: `Puzzle::Puzzle()' previously defined here
The problem is that you have defined Puzzle::Puzzle()
in both the header and the .cpp file, so it has two definitions.
The initializer list can go along with the constructor definition in the .cpp file:
Puzzle::Puzzle()
: puzzle (16)
{
// ...
}
and remove the definition from the header:
Puzzle(); // I'm just a declaration now, not a definition
The main problem is you define your constructor twice - once in the header, then again in the cpp file. Remove the one in the header and move the initialization to the cpp:
Puzzle::Puzzle()
: puzzle (16)
{
// Initialize the puzzle (0,1,2,3,...,14,15)
for(int i = 0; i <= puzzle.size(); i++)
{
puzzle[i] = i;
}
}
Moreover, unless you are using std::vector
- or worse, using namespace std
- in your header (which you shouldn't), your vector should be declared like this in the header:
std::vector<int> puzzle;
You can't initialise something in two different places. In the header, just declare it:
Puzzle();
in the .cpp file define it:
Puzzle::Puzzle() : puzzle( 16 )
{
// Initialize the puzzle (0,1,2,3,...,14,15)
for(int i = 0; i < puzzle.size(); i++)
{
puzzle[i] = i;
}
}
though you would probably be better off not using an initialisation list:
Puzzle::Puzzle()
{
// Initialize the puzzle (0,1,2,3,...,14,15)
for(int i = 0; i < 16; i++)
{
puzzle.push_back( i );
}
}
You can not define the constructor twice! So in the header file replace
Puzzle() : puzzle (16) {}
by
Puzzle();
And in the .cpp source file add
puzzle.resize(16);
in the first line.
精彩评论