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

&c 和 c 请看红字部分

waja 发布于 2014-03-18 15:16, 457 次点击
class Complex
{
private :
    float Real, Image;
public:
    Complex(float x = 0, float y = 0)
    {
        Real = x;
        Image = y;
    }
    void Show(int i)
    {
        cout << "c" << i << "=" << Real << "+" << Image << "i" << endl;
    }
    Complex operator + (Complex c);//////////////////////////请问这里书籍上给的是&c 但是这里用c结果一样
    Complex operator - (Complex &c);/////////////////////////为什么要用&c
    void  operator += (Complex &c);
    void operator = (Complex &c);
};



Complex Complex :: operator + (Complex c)///////////////////
{
    Complex t;
    t.Real =  Real + c.Real;
    t.Image = Image + c.Image;
    return  t;
}


Complex Complex :: operator -(Complex &c)/////////////////////////
{
    Complex t;
    t.Real = Real - c.Real;
    t.Image = Image - c.Image;
    return t;
}

void Complex :: operator += (Complex &c)
{
    Real = Real + c.Real;
    Image = Image + c.Image;
}

void Complex :: operator = (Complex &c)
{
  Real  = c.Real;
  Image = c.Image;
}

void main()
{
    Complex c1(15,34), c2(30,57),c3,c4;
    c1.Show(1);
    c2.Show(2);
    c3 = c1 + c2;
    c4 = c1 - c2;
    c3.Show(3);
    c4.Show(4);
    c2 += c1;
    c2.Show(5);


}


1 回复
#2
lonely_212014-03-18 15:23
   Complex operator + (Complex c);//////////////////////////请问这里书籍上给的是&c 但是这里用c结果一样   
    Complex operator - (Complex &c);/////////////////////////为什么要用&c
参数用&表示是引用的意思,这样会节省空间,不会产生中间临时变脸
如下:
int fun1(int a)
{
   a=10;
}
int fun2(int &a)
{
    a=10;
}

int main()
{
    int b=3;
    fun1(b);//调用fun1函数后,b还是3,因为在fun1函数中,改变的是中间变量的值
    fun2(b);//但调用fun2函数后,b就变成10了,此处改变的是b变量的值
    return 0;
}
1