我听说,当类中存在指针时,C++ 中应该始终存在复制构造函数和 = 运算符重写。我搜索了一下,没有找到关于指针何时指向类对象的解释。
为了说明我的问题:
class Figure
{
Figure();
Figure(const Figure& figure)
Figure(float density);
~Figure();
virtual float volume()=0;
Figure *next;
protected:
float density;
};
class Sphere: public Figure
{
Sphere();
Sphere(float r);
Sphere(float r, float density);
~Sphere();
float volume();
private:
float r;
};
我尝试为类Figure 制作一个复制构造函数。我在最后一行收到错误“不允许抽象类类型图的对象”。我不知道我做错了什么。而且我不知道如何覆盖赋值运算符。
Figure::Figure(const Figure& figure)
{
this->tip = figure.tip;
this->density = figure.density;
if (figure.next)
next = new Figure(*figure.next);
}
最佳答案
对此的典型解决方案是将所需的操作抽象化,并在子类中支持它。
class Figure {
virtual Figure * clone() const = 0;
};
class Sphere : public Figure {
Figure * clone() const {
return new Sphere(*this);
}
};
然后当然要正确实现 Sphere 复制构造函数。
关于c++ - 如何使用类对象上的指针在类中定义复制构造函数和 = 运算符重写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5492879/