HN *_*ner 7 c++ operator-overloading friend-function
以前我学会了用C++重载Operators作为成员函数以及类的友元函数.虽然,我知道如何使用这两种技术在C++中重载运算符.但我仍然感到困惑,**哪一个更好**?成员函数或朋友函数重载运算符,我应该使用哪个,为什么?请指导我!您的回复将受到极大的赞赏.我很高兴并感谢你的回答.
选择不是“会员或朋友”,而是“会员或非会员”。
(友谊经常被过度使用,而且通常在学校教得太早。)
这是因为您始终可以添加一个自由函数可以调用的公共成员函数。
例如:
class A
{
public:
explicit A(int y) : x(y) {}
A plus(const A& y) const { return A{x + y.x}; }
private:
int x;
};
A operator+(const A& lhs, const A& rhs) { return lhs.plus(rhs); }
Run Code Online (Sandbox Code Playgroud)
至于如何选择:如果操作符不把类的一个实例作为它的左手操作数,它必须 是一个自由函数,否则这几乎是个人品味的问题(或者编码标准,如果你不是独自的)。
例子:
// Can't be a member because the int is on the left.
A operator+ (int x, const A& a) { return A{x} + a; }
Run Code Online (Sandbox Code Playgroud)
对于具有相应变异运算符(如+和 +=)的运算符,通常将变异运算符作为成员,另一个作为非成员:
class B
{
public:
explicit B(int y) : x(y) {}
B& operator+= (const B& y) { x += y.x; return *this; }
private:
int x;
};
B operator+(B lhs, const B& rhs) { return lhs += rhs; }
Run Code Online (Sandbox Code Playgroud)
但是你当然也可以把它拼出来:
class C
{
public:
explicit C(int y) : x(y) {}
C& add(const C& y) { x += y.x; return *this; }
private:
int x;
};
C& operator+=(C& lhs, const C& rhs) { return lhs.add(rhs); }
C operator+(C lhs, const C& rhs) { return lhs += rhs; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3661 次 |
| 最近记录: |