注册 登录
编程论坛 C++教室

关于“重载运算符和友元函数参数关系”的问题

hmsabc 发布于 2010-08-14 11:50, 749 次点击
程序代码:
//重载运算符和友元函数
#include<iostream>
using namespace std;

class Complex
{
public:
    Complex( ){ real=0;imag=0;}
    Complex( double r,double i):real(r),imag(i){ }
    friend Complex operator + (Complex &c1,Complex &c2);             //重载函数作为友元函数
    void display( );

private:
    double real;
    double imag;
};

Complex operator + (Complex &c1,Complex &c2)                        //定义作为友元函数的重载函数
{ return Complex(c1.real + c2.real,c1.imag + c2.imag);}

void Complex::display( )
{ cout << "(" << real << "," << imag <<"i)" << endl;}

int main( )
{
    Complex c1(3,4),c2(5,-10),c3;
    c3 = c1 + c2;
    cout << "c1 = ";c1.display( );
    cout << "c2 = ";c2.display( );
    cout << "c1 + c2 = ";c3.display( );
    system("pause");
    return 0;
}

/*
请问:如果想把类中申明友元函数的 friend 去掉,就是说,把 Complex operator+ ( Complex &c1,Complex &c2) 作
为 Complex 类的成员函数,行不行呢?为什么?你能保证在有两个参数的前提下,不用友元关系,使程序正常运行吗?
*/

2 回复
#2
pangding2010-08-14 12:25
operator+ 是一个二元操作符。
如果是友元函数的话,写 c1 + c2 是时候,就把这两个对象分别作参数传过去。执行 operator+ (c1, c2);
如果是成员函数的话,写 c1 + c2,是按这种方法调用的 c1.operator+(c2),一个参数就是 c2 本身,另一个参数则是靠 this 指针隐式传递的。它无法接受第三个参数,所以我想你要的那种写法可能不行。我没试过,也不一定语法上过不了,你可以自己试试。
一般来说,能不用友元解决的问题,不用友元会更好一点。不过也有例外~
#3
最近不在2010-08-14 14:58
当然可以...返回值可传给一个临时对象,也可以传给*this;不过这样的话,*this对象本身的值就凉在一边了.
如 A obj1(1),obj2(2),obj3(10);
obj3 = obj1 + obj2;
obj2 = 3;
1