为什么需要用friend关键字?
代码如下:
//---------------------------------------
#include <vcl.h> //不得不要
#include <iostream>
using namespace std;
//---------------------------------------
class Complex
{
public:
Complex(double r=0.0, double i=0.0) { real = r; imag = i; }
void display() const { cout<<real<<'+'<<imag<<'i'; }
Complex add(const Complex& x)const ;
void complex_add(const Complex& x, const Complex& y); //非友元,为什么可行?
//friend
Complex complex_add2(const Complex& x, const Complex& y);
private:
double real;
double imag;
};
//---------------------------------------
//如何实现两个复数相加?
Complex Complex::add(const Complex& x) const
{
Complex temp;
temp.real = this->real + x.real;
temp.imag = this->imag + x.imag;
return temp;
}
//---------------------------------------
void Complex::complex_add(const Complex& x, const Complex& y) //非友元函数
{
this->real = x.real + y.real;
this->imag = x.imag + y.imag;
}
//---------------------------------------
Complex complex_add2(const Complex& x, const Complex& y) //一定要是友元函数?为什么?
{
Complex temp;
temp.real = x.real + y.real; //非友元情况下temp不能访问real,为什么?
temp.imag = x.imag + y.imag;
return temp;
}
//---------------------------------------
//测试代码:
int main(int argc, char* argv[])
{
Complex a(1.0, 2.0), b(3.0, 5.0), c;
//c = a.add(b); // OK
//c.complex_add(a,b); // OK
c = complex_add2(a,b); // ?why
c.display();
return 0;
}
//---------------------------------------
第二个void complex_add(const Complex& x, const Complex& y) 是 this = x + y,没有返回值,不管原先的this是什么值,最终是被x+y替代。这个add函数和通常的加法含义有区别。
第三个friend Complex complex_add2(const Complex& x, const Complex& y) 实现x+y,返回一个复数,是复数加法的友元函数的实现。没有this指针的参与,当然要加friend定义友元函数。
[解决办法]
既然是成員函數了
c = complex_add2(a,b); // ?why
這樣的調用就是錯的了.
你要這樣調用
c = complex_add2(a,b); // ?why
就把它改回友元函數.
這樣你應該明白友元函數的好處了.
[解决办法]
参数表中同类型的参数是可以访问私有成员的,这个有点奇怪啦,要记住。
你的temp是你新建的一个对象,他与参数表中的对象是不同的,不可以直接访问私有成员