我的Puzzle.h中有以下内容
class Puzzle
{
private:
vector<int> puzzle;
public:
Puzzle() : puzzle (16) {}
bool isSolved();
void shuffle(vector<int>& );
};然后我的Puzzle.cpp看起来像这样:
Puzzle::Puzzle()
{
// Initialize the puzzle (0,1,2,3,...,14,15)
for(int i = 0; i <= puzzle.size(); i++)
{
puzzle[i] = i;
}
}
// ... other methods我是否在我的头文件中使用了错误的初始化器列表?我想定义一个整数向量,并将其大小初始化为16,我该怎么做呢?
G++输出:
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发布于 2010-04-19 04:30:12
问题是您在头文件和.cpp文件中都定义了Puzzle::Puzzle(),所以它有两个定义。
初始化器列表可以与.cpp文件中的构造函数定义一起使用:
Puzzle::Puzzle()
: puzzle (16)
{
// ...
}并从标题中删除定义:
Puzzle(); // I'm just a declaration now, not a definition发布于 2010-04-19 04:29:08
主要的问题是你定义了两次构造函数--一次在头文件中,一次在cpp文件中。删除header中的一个,并将初始化移至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;
}
}此外,除非你在你的头中是using std::vector -或者更糟,using namespace std -在你的头中(你不应该这样),你的向量应该这样在头中声明:
std::vector<int> puzzle;发布于 2010-04-19 04:31:45
你不能在两个不同的地方初始化一些东西。在标题中,只需声明它:
Puzzle();在.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;
}
}尽管不使用初始化列表可能会更好:
Puzzle::Puzzle()
{
// Initialize the puzzle (0,1,2,3,...,14,15)
for(int i = 0; i < 16; i++)
{
puzzle.push_back( i );
}
}https://stackoverflow.com/questions/2663814
复制相似问题