我最初的评论虽然有点轻率,但仍然正确。话虽如此,我将您的问题重新实现为可以编译以演示解决方案的东西。
首先,您的类(如图所示)不需要赋值运算符重载。它也不需要复制构造函数、析构函数、移动构造函数或移动赋值运算符。这是因为您没有保持任何动态,因此内置的浅拷贝/分配就足够了。
话虽如此,我重新实现了你的operator+()
以稍微更惯用的方式。如果你能做到Derived + Derived
,人们期望能够做到Derived += Derived
以及。
因为这些是相互关联的,所以可以实现operator+()
按照 operator+=()
。唯一的技巧是利用值传递。
这是代码:
#include <iostream>
class Base {
public:
Base() = default;
Base(int x, int y) : m_x(x), m_y(y) {}
// Assignment operator not required, Rule of 0
Base& operator+=(const Base& rhs) {
m_x += rhs.m_x;
m_y += rhs.m_y;
return *this;
}
friend Base operator+(Base lhs, const Base& rhs) {
lhs += rhs;
return lhs;
}
// Needed to print a Derived object
protected:
int getX() const { return m_x; }
int getY() const { return m_y; }
private:
int m_x = 0;
int m_y = 0;
};
class Derived : public Base {
public:
Derived() = default;
Derived(double rho, double phi) : Base(), m_rho(rho), m_phi(phi) {}
Derived(int x, int y, double rho, double phi)
: Base(x, y), m_rho(rho), m_phi(phi) {}
Derived& operator+=(const Derived& other) {
Base::operator+=(other);
m_rho += other.m_rho;
m_phi += other.m_phi;
return *this;
}
friend Derived operator+(Derived lhs, const Derived& rhs) {
lhs += rhs;
return lhs;
}
friend std::ostream& operator<<(std::ostream& sout, const Derived& rhs) {
return sout << "x: " << rhs.getX() << "\ny: " << rhs.getY()
<< "\nrho: " << rhs.m_rho << "\nphi: " << rhs.m_phi;
}
private:
double m_rho = 0.0;
double m_phi = 0.0;
};
int main() {
Derived d1;
Derived d2(2, 2, 1.1, 1.1);
Derived d3 = d1 + d2;
Derived d4 = d2 + d3;
std::cout << "\nd4:\n" << d4 << '\n';
std::cout << "\nd3:\n" << d3 << '\n';
std::cout << "\nd2:\n" << d2 << '\n';
}
Output:
d4:
x: 4
y: 4
rho: 2.2
phi: 2.2
d3:
x: 2
y: 2
rho: 1.1
phi: 1.1
d2:
x: 2
y: 2
rho: 1.1
phi: 1.1
你可以看到我做了“同样的事情”。在我的operator+=()
,我称之为Base
版本第一。然后我照顾Derived
成员。这是有效的,因为虽然operator+=()
返回一个引用,operator+()
采取其lhs
按值传递参数,这意味着它是一个副本。副本被更改为operator+=()
然后回来了。利用按值传递的优势让我可以使用operator+=()
不改变任何一个原始操作数。所以operator+()
仍然表现如预期。