您的位置:首页 > 编程语言 > C语言/C++

C++ 重载运算符 运算符重载函数作为类成员函数 重载运算符+

2017-09-20 19:27 204 查看
用运算符重载函数作为类成员函数的方法重载运算符+

下面的例子来自于课本:

#include <iostream>
using namespace std;

class Complex
{
public:
Complex() //无参构造函数
{
real = 0;
imag = 0;
}
Complex(double r, double i) //有参构造函数
{
real = r;
imag = i;
}
Complex operator + (Complex &c2); //声明重载运算符
void display(); //成员函数,对类中的变量进行输出

private:
double real;
double imag;
};

Complex Complex::operator +(Complex &c2)
{
Complex C;
C.real = real + c2.real;
C.imag = imag + c2.imag;
return C;
}

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;
}
主函数中执行c1+c2语句,是调用了运算符重载函数operator +;

相当于c1.operator + ( );

运行结果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: