在c++的子类中使用基类的操作符重载定义



我目前正在深入研究c++。我有一个多态性/继承的问题,我不能弄清楚,并没有找到网上的答案,似乎(对我来说),以解决我的具体问题:

我想有一个基类和几个派生子类。我想在子类访问的基类中定义通用函数/操作符重载,以避免代码重复。

这是我想弄明白的例子:

class ElectricalUnit {
protected:
float value;
public:
ElectricalUnit(float _value) : value(_value) {};
float getValue() const {
return this->value;
}
// this should be the (only) place where the add operation for all subclasses is defined
// note: I intentionally want to avoid changing the objects' state by returning a new object
ElectricalUnit operator+ (const ElectricalUnit& other) const {
return ElectricalUnit(this->value + other.getValue());
}
};

class Voltage : public ElectricalUnit {
public:
Voltage(float _voltage) : ElectricalUnit(_voltage) {};
float getVoltage() const {
return ElectricalUnit::getValue();
}
Voltage operator+ (const Voltage& other) {  // not having this function did not work
// 1st try:
return ElectricalUnit::operator+(other); // error: says no conversion is available??
// 2nd try:
return (Voltage)ElectricalUnit::operator+(other); // error: also says no conversion is available.
// 3rd try (read it online)
ElectricalUnit::operator+(other);
return *this;  // does give wrong values, because the return value of operator+ is not used
}
};

class Current : public ElectricalUnit {
private:
float current;
public:
Current(float current) : current(current) {};
float getCurrent() { return this->current; };
/* use operator+ method from base class --> but how? */
};

其中,VoltageCurrent来源于基类ElectricalUnit。在每个子类中添加电压或电流(或其他如功率,能量等)是相同的。因此,在ElectricalUnit中,我定义了操作符重载方法,并希望子类使用此方法。当考虑公差等时,操作可能会变得更加复杂。我的目标是只有一个方法来实现逻辑。

下面是一个示例程序:
int main() {
Voltage u1 = { 4 };
Voltage u2 = { 6 };
Voltage u3 = u1 + u2;
Voltage u4 = u3 + u2;

std::cout << "Voltage U1 = " << u1.getVoltage() << " V" << std::endl;
std::cout << "Voltage U2 = " << u2.getVoltage() << " V" << std::endl;
std::cout << "Voltage U3 = " << u3.getVoltage() << " V" << std::endl;
std::cout << "Voltage U4 = " << u4.getVoltage() << " V" << std::endl;
return 0;
}

我怎么做到这一点,还是我误解了什么?我是一名Python程序员,这里的工作完全不考虑类型^^

我很高兴每一个帮助:)谢谢。

Voltage::operator+返回值有一个转换问题,因为多态性只适用于指针和引用。函数返回一个值,而您试图返回ElectricalUnit,而Voltage应该返回。

你需要做的是根据ElectricalUnit::operator+的返回值显式地创建一个新的Voltage实例,如下所示。

Voltage operator+(const Voltage& other)
{
return Voltage(ElectricalUnit::operator+(other).getValue());
}

最新更新