我正在寻找以下“问题”的优雅解决方案:
考虑类 Base 和 Child,以及此处 operator+ 的工作方式:
class Base
{
public:
Base(int a=0) : mValue(a) {};
Base(const Base& rhs) : mValue(rhs.mValue) {};
Base& operator=(const Base& rhs) {
if (this==&rhs) return *this;
mValue=rhs.mValue;
}
friend const Base operator+(Base &lhs, Base &rhs);
private:
int mValue;
};
const Base operator+(Base &lhs, Base &rhs)
{
Base result(lhs.mValue+rhs.mValue);
return result;
}
class Child : public Base
{
public:
Child(int a=0) : Base(a) {};
};
int main()
{
Child a(2);
Child b(5);
Child c(a+b); // **** This line ****
Child d;
d=(a+b); // **** or this other one ****
}
main 中标记的行给出了错误: 无法从“const Base”转换为“Child”
我完全理解,运算符已经定义在Base类中,返回的是Base类型的对象,无法转换为Child 。 一种解决方案是为 Child 类重载 operator+,但我想知道是否有更好、成本更低的方法。我的印象是我忘记了一个更简单的选择。谢谢!
最佳答案
你可以定义一个构造函数 Child(Base& obj)
然后 Child c=(a+b);
语句就可以了然后你可以使用基础对象作为根据您的要求。
关于c++ - 重载运算符+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22507001/