【发布时间】:2021-07-09 13:12:21
【问题描述】:
好吧,伙计们,这让我很困惑,尤其是因为网上的信息太少了......
好吧,假设我有一个父类和一个子类:
class ParentPlot
{
public:
int a;
int b;
datacontainer Events;
friend ParentPlot& operator+(ParentPlot& plotA, const ParentPlot& plotB)
{
//add stuff
return sumPlot;
}
virtual ParentPlot operator+=(const ParentPlot &plotB)
{
//+= stuff using 'this'
return *this;
}
}
class ChildPlot: public ParentPlot
{
public:
int q;
friend ChildPlot& operator+(ChildPlot& plotA, const ChildPlot& plotB)
{
//Static cast and add the parents.
ParentPlot PlotACast = static_cast<ParentPlot>(plotA); //2 Static casts
ParentPlot PlotBCast = static_cast<ParentPlot>(plotB);
ParentPlot ParentSum = PlotACast + PlotBCast; //Add as ParentPlots
ChildPlot BasePlot = ChildPlot(ParentSum);
//Add child members
BasePlot.q = plotA.q + plotB.q;
return BasePlot;
}
ChildPlot& operator+=(const ChildPlot& plotB)
{
//How do I correctly implement this?
}
}
我应该如何正确管理这些类的添加和 +=?每个组合似乎都会产生某种错误,我无法让它发挥作用。例如上面实现的方法给出了以下错误:
"这个算子函数的参数太少"
我曾尝试将 ParentPlot 设为抽象类,然后仅在子类中实现,但随后加法运算符中断,因为我无法在加法运算符中返回父级。
从技术上讲,ParentPlot 将是抽象的,但会有许多需要求和的子节点,并且它有多个成员。我不应该为父母和孩子实现加法运算符或 += 还是我错过了什么? Genuinly 不知道处理这个问题的正确方法。任何想法都会有所帮助...
谢谢
【问题讨论】:
-
+无法返回引用,因为它需要创建一个新对象。 (虚拟运算符通常不像您最初想象的那么好。) -
不应该 += 不返回作为参考的“this”吗?
-
this是指针,而不是引用。+=预计将通过引用返回*this,修改后的对象(您可以通过不返回任何内容来解决切片问题)。另一方面,您的+正在返回对BasePlot的引用,这是一个自动对象,并在函数返回时被销毁。 -
作为一般的经验法则,变异操作符——比如
+=——返回一个对修改对象的引用,*this。非变异运算符 - 如+- 按值返回一个新对象。
标签: c++ inheritance operator-overloading operators abstract-class