如何解决在 C++ 中的父类和子类中重载 + 和 += 运算符 1.修复您的运算符返回类型2.使用 operator +3.实现子operator +=完整代码see it online:
好吧伙计们,这个让我很困惑,尤其是因为网上关于这方面的信息太少了...
好吧,假设我有一个父类和一个子类:
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 将是抽象的,但会有许多需要求和的子级,并且它有多个成员。我不应该为父级和子级实现加法运算符或 += 还是我错过了什么?真的不知道处理这个问题的正确方法。任何想法都会有所帮助...
谢谢
解决方法
1.修复您的运算符返回类型。
operator +
应该返回一个副本。 operator +=
应返回对 this
的引用。
friend ParentPlot operator+(ParentPlot& plotA,const ParentPlot& plotB)
ParentPlot& operator+=(const ParentPlot &plotB)
friend ChildPlot operator+(ChildPlot& plotA,const ChildPlot& plotB)
ChildPlot& operator+=(const ChildPlot& plotB)
2.使用 operator +
实现您的 operator +=
这个小技巧使您的代码变得干燥,并且可以更轻松地实现那些额外的运算符。
请注意,第一个参数是按值获取的,我们需要一个将被 operator +=
修改的副本。
friend ParentPlot operator+(ParentPlot plotA,const ParentPlot& plotB)
{
return plotA += plotB;
}
friend ChildPlot operator+(ChildPlot plotA,const ChildPlot& plotB)
{
return plotA += plotB;
}
3.实现子operator +=
假设您已经拥有 operator +=
的 ParentPlot
,您可以通过两种方式使用它:
static_cast<ParentPlot&>(*this) += plotB;
//or
ParentPlot::operator+=(plotB);
然后像往常一样添加特定于孩子的实现和 return *this;
。
完整代码(see it online):
class ParentPlot {
public:
int a;
int b;
friend ParentPlot operator+(ParentPlot plotA,const ParentPlot& plotB)
{
return plotA += plotB;
}
ParentPlot& operator+=(const ParentPlot& plotB)
{
a += plotB.a;
b += plotB.b;
return *this;
}
};
class ChildPlot : public ParentPlot {
public:
int q;
friend ChildPlot operator+(ChildPlot plotA,const ChildPlot& plotB)
{
return plotA += plotB;
}
ChildPlot& operator+=(const ChildPlot& plotB)
{
//static_cast<ParentPlot&>(*this) += plotB;
ParentPlot::operator+=(plotB);
q += plotB.q;
return *this;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。