所以,我得到了这样的代码:
class Fruit
{//some constructor method and instance in here}
class Banana: public Fruit
{//some constructor method and instance in here}
class plant
{
public:
plant(){
thisFruit->Banana();//everytime a new plant is created, its thisFruit will point to a new Banana Object
}
private:
Fruit *thisFruit;//this plant has a pointer to a fruit
}
然而,我在“this-Fruit-> banana();”中收到错误。那状态“不允许指向不完整类类型的指针。我的代码有问题吗?thx
答案 0 :(得分:2)
如果您希望thisFruit
指向香蕉对象,则需要使用thisFruit
对象初始化Banana
plant::plant()
: thisFruit(new Banana())
{
}
当您将本机指针作为成员时,请确保遵循rule of three。 读取rule of zero,因为C ++ 11即将来临。
答案 1 :(得分:1)
此
thisFruit->Banana();
没有任何意义。你可能意味着
thisFruit = new Banana();
确保在析构函数中delete thisFruit
并提供合适的assignemt运算符。或者让自己轻松生活并使用智能指针,例如: boost::scoped_ptr<Fruit>
或std::unique_ptr<Fruit>
。
答案 2 :(得分:1)
您必须使用std::unique_ptr
或其他智能指针并使用新的Banana
进行初始化:
#include <memory>
class Fruit {
//some constructor method and instance in here
}
class Banana : public Fruit {
//some constructor method and instance in here
}
class Plant {
public:
Plant() : thisFruit{new Banana} {
}
private:
std::unique_ptr<Fruit> thisFruit; //this plant has a pointer to a fruit
}