C++中运算符重载的方法
生活随笔
收集整理的這篇文章主要介紹了
C++中运算符重载的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
**#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;}**
在進行運算的時候c2為實參調用c1的運算重載函數operator + (Complex &c2),進行求值,得到兩個復數之和,注意上面的operator +是一個函數名,它是Complex的成員函數。
總結
以上是生活随笔為你收集整理的C++中运算符重载的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 作者:窦勇(1966-),男,博士,国防
- 下一篇: Python_opencv