f********a 发帖数: 1109 | 1 算符重载很方便,比方说:
class complex
{
public:
complex(double r, double i){
real = r, imag = i;}
complex operator +(const complex & c);//算符重载
};
为什么有人用友员来实现算符重载, 有什么好处?
class complex
{
public:
complex(double r, double i){
real = r, imag = i;}
friend complex operator +(const complex &c1, const complex &c2);//友员
};
查了好多书都没有提到有什么好处。。 | f********a 发帖数: 1109 | 2 前面一种用法 A = B + C;
可以阿,编译通过的。 | o******r 发帖数: 259 | 3 Sorry,记错了,
当需要access两个class的 private data时用friend function.
另外,当操作符左边是class object的时候, 才会调用class member,
否则用friend function,
比如2个String相加,
String myStr;
"abcd" + myStr 最好定义friend function
【在 f********a 的大作中提到】 : 前面一种用法 A = B + C; : 可以阿,编译通过的。
| p****o 发帖数: 1340 | 4 friend functions can also take advantage of implicit conversion. but
it is arguable whether this is good or not.
【在 o******r 的大作中提到】 : Sorry,记错了, : 当需要access两个class的 private data时用friend function. : 另外,当操作符左边是class object的时候, 才会调用class member, : 否则用friend function, : 比如2个String相加, : String myStr; : "abcd" + myStr 最好定义friend function
|
|