Com*_*123 0 c++ constructor clone copy
我正在尝试实现 .cpp 文件中的 .h 文件中的虚拟函数。这是一个作业,所以我不能仅仅使该函数成为非虚拟函数。这是一个克隆函数,它调用类的复制构造函数。功能:
virtual Item* clone() const;
Run Code Online (Sandbox Code Playgroud)
在课堂上
Ingredient : public Item {
Run Code Online (Sandbox Code Playgroud)
当我在 Ingredient.cpp 文件中实现它时,我有:
Ingredient::clone () const {
return new Ingredient ( *this );
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试编译时,出现以下两个错误:
Ingredient.cpp:23:13:错误:C++ 需要所有声明的类型说明符
Ingredient::clone () const {
^
Run Code Online (Sandbox Code Playgroud)
Ingredient.cpp:24:9:错误:无法使用“Ingredient *”类型的右值初始化“int”类型的返回对象
return new Ingredient ( *this );
^~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
产生 2 个错误。
我不明白我在这里做错了什么,因为我应该使用取消引用的 *this self 指针。有什么建议么?
您忘记了函数实现中的返回类型。
Item* Ingredient::clone () const {
// ^^ Missing
Run Code Online (Sandbox Code Playgroud)