C++ 中的克隆函数
Clone function in C++
我正在尝试在我的 .cpp 文件中的 .h 文件中实现一个虚函数。这是一个任务,所以我不能只使函数非虚拟。这是一个克隆函数,它调用 class 的复制构造函数。函数:
virtual Item* clone() const;
在class
Ingredient : public Item {
当我在我的 Ingredient.cpp 文件中实现它时,我有:
Ingredient::clone () const {
return new Ingredient ( *this );
}
但是当我尝试编译时,出现了这两个错误:
Ingredient.cpp:23:13: 错误:C++ 需要所有声明的类型说明符
Ingredient::clone () const {
^
Ingredient.cpp:24:9: 错误:无法使用 'Ingredient *'
类型的右值初始化 'int' 类型的 return 对象
return new Ingredient ( *this );
^~~~~~~~~~~~~~~~~~~~~~~~
产生了 2 个错误。
我不明白我在这里做错了什么,因为我应该使用取消引用的 *this self 指针。有什么建议吗?
您忘记了函数实现中的 return 类型。
Item* Ingredient::clone () const {
// ^^ Missing
我正在尝试在我的 .cpp 文件中的 .h 文件中实现一个虚函数。这是一个任务,所以我不能只使函数非虚拟。这是一个克隆函数,它调用 class 的复制构造函数。函数:
virtual Item* clone() const;
在class
Ingredient : public Item {
当我在我的 Ingredient.cpp 文件中实现它时,我有:
Ingredient::clone () const {
return new Ingredient ( *this );
}
但是当我尝试编译时,出现了这两个错误:
Ingredient.cpp:23:13: 错误:C++ 需要所有声明的类型说明符
Ingredient::clone () const {
^
Ingredient.cpp:24:9: 错误:无法使用 'Ingredient *'
类型的右值初始化 'int' 类型的 return 对象 return new Ingredient ( *this );
^~~~~~~~~~~~~~~~~~~~~~~~
产生了 2 个错误。
我不明白我在这里做错了什么,因为我应该使用取消引用的 *this self 指针。有什么建议吗?
您忘记了函数实现中的 return 类型。
Item* Ingredient::clone () const {
// ^^ Missing