重载二元运算的正确方法
The proper way to overload binary operation
我是 C++ 新手,所以,请放轻松 :)
我发现了两种不同的方法来在 C++ 中重载二元运算符。
第一个(来自 "Object-Oriented Programming in C++" 书,Robert Lafore):
class Distance
{
private:
int value;
public:
Distance() : value(0) {}
Distance(int v) :value(v) {}
Distance operator+(Distance) const;
};
Distance Distance::operator+(Distance d2) const
{
return Distance(value+d2.value);
}
还有一个,使用friend funcs(来自网络)
class Distance
{
private:
int value;
public:
Distance() : value(0) {}
Distance(int v) :value(v) {}
friend const Distance operator+(const Distance& left, const Distance& right);
};
const Distance operator+(const Distance& left, const Distance& right)
{
return Distance(left.value + right.value);
}
所有这些情况都可以编写如下代码:
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2;
我的问题:这些案例的主要区别是什么?也许有一些优点或缺点。或者某种 "good programming manners"?
提前感谢您的智慧! :)
Distance
可以从 int
隐式转换。然后第二种风格使得可以将 opeartor+
与用作右操作数的 Distance
对象一起使用。
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5; //fine
Distance d5 = 5 + d1; //fine
第一种方式只支持使用opeartor+
,左操作数为Distance
的对象。即
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5; //fine
Distance d5 = 5 + d1; //fail
有几个细微差别,包括:
非会员方式允许同时拥有
42 + Distance(42);
Distance(42) + 42;
而会员方式只允许
Distance(42) + 42;
我是 C++ 新手,所以,请放轻松 :) 我发现了两种不同的方法来在 C++ 中重载二元运算符。
第一个(来自 "Object-Oriented Programming in C++" 书,Robert Lafore):
class Distance
{
private:
int value;
public:
Distance() : value(0) {}
Distance(int v) :value(v) {}
Distance operator+(Distance) const;
};
Distance Distance::operator+(Distance d2) const
{
return Distance(value+d2.value);
}
还有一个,使用friend funcs(来自网络)
class Distance
{
private:
int value;
public:
Distance() : value(0) {}
Distance(int v) :value(v) {}
friend const Distance operator+(const Distance& left, const Distance& right);
};
const Distance operator+(const Distance& left, const Distance& right)
{
return Distance(left.value + right.value);
}
所有这些情况都可以编写如下代码:
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2;
我的问题:这些案例的主要区别是什么?也许有一些优点或缺点。或者某种 "good programming manners"?
提前感谢您的智慧! :)
Distance
可以从 int
隐式转换。然后第二种风格使得可以将 opeartor+
与用作右操作数的 Distance
对象一起使用。
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5; //fine
Distance d5 = 5 + d1; //fine
第一种方式只支持使用opeartor+
,左操作数为Distance
的对象。即
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5; //fine
Distance d5 = 5 + d1; //fail
有几个细微差别,包括:
非会员方式允许同时拥有
42 + Distance(42);
Distance(42) + 42;
而会员方式只允许
Distance(42) + 42;