C++ 重载运算符 友元函数作为重载运算符 重载运算符+

以友元函数作为重载运算符的方式重载运算符+

下面的例子来自于课本

#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();

    return 0;
}

此主函数中执行c3 = c1 + c2调用了重载运算符operator +;

并且此重载运算符函数是Complex的友元函数。

必须是Complex对象相加才可以。

运行结果:



读者可以自行对比一下友元函数为重载运算符函数和成员函数作为重载运算符函数的区别:http://blog.csdn.net/z_dream_st/article/details/78044481


发布了35 篇原创文章 · 获赞 18 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Z_Dream_ST/article/details/78044651