我在继承重载的 + 运算符时遇到了问题。 让我举个例子。
class Data{
protected:
int data[3];
public:
Data(){
data[0] = data[1] = data[2] = 0;
}
Data operator+(const Data& other)
{
Data temp = *this;
for(int i=0;i<3;i++){
temp.data[i] += other.data[i]
}
return temp;
}
};
class DataInterited:public Data{
public:
};
/******************Main*****************/
DataInterited d1,d2,d3;
d3 = d1 + d2; //=> This is compile error
这段代码生成编译错误说,
no match for ‘operator=’ (operand types are ‘DataInterited’ and ‘Data’)
我认为我必须为 DataInherited
实现 operator+
以便它返回 DataInherited
实例。 但这样一来,我就无法避免代码重复。
有什么方法可以使 d3=d1+d2;
行正确同时避免重复 + operator
实现?
最佳答案
有几件事你需要知道。
首先,始终将 operator+
实现为 operator+=
的自由函数。它可以节省代码重复并且效率最高。
其次,您在 DataInherited
中没有可以将 Data
作为其参数的构造函数。这很重要,因为 Data::operator+
的结果是数据,而不是 DataInherited
。
更正后的代码:
#include <iostream>
#include <algorithm>
class Data{
protected:
int data[3];
public:
Data(){
data[0] = data[1] = data[2] = 0;
}
Data(const Data& other)
{
std::copy(std::begin(other.data), std::end(other.data), data);
}
Data& operator=(const Data& other)
{
std::copy(std::begin(other.data), std::end(other.data), data);
return *this;
}
Data& operator+=(const Data& other)
{
for(int i=0;i<3;i++){
data[i] += other.data[i];
}
return *this;
}
};
Data operator+(Data left, const Data& right)
{
return left += right;
}
class DataInterited:public Data{
public:
DataInterited(Data d = {})
: Data(std::move(d))
{}
};
using namespace std;
auto main() -> int
{
DataInterited d1,d2,d3;
d3 = d1 + d2; //=> This is no longer a compile error
return 0;
}
关于c++ - 重载 + 运算符的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32365696/