运算符重载 类 C++

/*
运算符重载
就是对已有的运算符(C ++中预定义的运算符)赋予多重的含义,
是同一个运算符作用与不同类型的数据是导致不同类型的行为

实质:函数重载
1 可以重载为普通函数也可以重载为成员函数
2 把含运算符的表达式转换成对运算符函数的调用
3 把运算符的操作数转换 成 运算符函数的参数
4 运算符被多次重载时,根据实参的类型决定调用哪个运算符函数

目的:扩展C++中提供的运算符的适用范围,使之能作用于对象。
 
同一运算符,对不同类型的操作数,所发生的行为不同

格式:
    返回类型 operator 运算符(参数表)
    {
    }
*/
#if 0
#include <iostream>
using namespace std;

class Complex
{
    public:
        double real , imag ;
        Complex( double r = 0.0 , double i = 0. ):real(r),imag(i)
        {
        }
        Complex operator-( const Complex & c );
};

Complex operator+( const Complex & a , const Complex & b )
{
    return Complex ( a.real + b.real , a.imag + b.imag );//返回临时对象
}

Complex Complex::operator-( const Complex & c )
{
    return Complex( real - c.real , imag - c.imag );//返回临时对象
}
//重载为成员函数时,参数个数为运算符数目减一
//重载为普通函数时,参数个数为运算符个数

int main()
{
    Complex a ( 4 , 4 ) , b ( 1 , 1 ), c ;
    c = a + b ;//c = operator +(a,b)
    cout << c.real << "," << c.imag << endl ;
    cout << (a-b).real << "," << (a-b).imag << endl ;//a-b=a.operator-(b)
    return 0;
}
#endif

猜你喜欢

转载自blog.csdn.net/qq_40990854/article/details/80078817
今日推荐