5 c++ symmetric operator-overloading
我正在学习C++,我想知道我是否能够深入了解创建两种不同类型实例的二元运算符的首选方法.这是我用来说明我的担忧的一个例子:
class A;
class B;
class A
{
private:
int x;
public:
A(int x);
int getX() const;
int operator + (const B& b);
};
class B
{
private:
int x;
public:
B(int x);
int getX() const;
int operator + (const A& A);
};
A::A(int x) : x(x) {}
int A::getX() const { return x; }
// Method 1
int A::operator + (const B& b) { return getX() + b.getX(); }
B::B(int x) : x(x) {}
int B::getX() const { return x; }
// Method 1
int B::operator + (const A& a) { return getX() + a.getX(); }
// Method 2
int operator + (const A& a, const B& b) { return a.getX() + b.getX(); }
int operator + (const B& b, const A& a) { return a.getX() + b.getX(); }
#include <iostream>
using namespace std;
int main()
{
A a(2);
B b(2);
cout << a + b << endl;
return 0;
};
Run Code Online (Sandbox Code Playgroud)
如果我想在这两种类型中具有对称性,那么哪种方法是上述代码中的最佳方法.选择一种方法比另一种方法有任何可能的危险吗?这是否随退货类型而变化?请解释!谢谢!
最好的方法是定义(在任一类之外)int operator+ (const A& a, const B& b),并在需要时使它成为两个类的友元函数.另外,定义
int operator+(const B& b, const A& a) {return a + b;}
Run Code Online (Sandbox Code Playgroud)
使其对称.