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

c++的运算符重载

2017-06-21 10:50 106 查看
C++中的加号重载:

如何实现复数的相加:#include<iostream>
using namespace std;

class Complex{
public:
Complex(double r=0.0,double i=0.0):real(r),imag(i){}
Complex operator+(const Complex &c2)const;
void display()const{
cout<<"("<<real<<","<<imag<<')'<<endl;
}
private:
double real,imag;
};
Complex Complex::operator+(const Complex &c2)const{
return Complex(real+c2.real,imag-c2.imag);
}

int main(){
Complex c1(5,4),c2(2,10),c3;
c3=c1+c2;
c3.display();
return 0;
}C++中的前置++重载:
点的移动:

#include<iostream>
using namespace std;

class Point{
public:
Point(float a,float b):x(a),y(b){}
Point& operator++();
~Point(){}
void dispaly()const{
cout<<"("<<x<<","<<y<<")"<<endl;
}
private:
float x,y;
};
Point& Point::operator++(){
x++;y++;
return *this;
}

int main(){
Point p(1,2);
(++p).dispaly();
p.dispaly();
return 0;
}C++中的后置++重载:
点的移动:

#include<iostream>
using namespace std;

class Point{
public:
Point(float a,float b):x(a),y(b){}
Point operator++(int);
~Point(){}
void dispaly()const{
cout<<"("<<x<<","<<y<<")"<<endl;
}
private:
float x,y;
};
Point Point::operator++(int){
Point p=*this;
x++;y++;
return p;
}

int main(){
Point p(1,2);
(p++).dispaly();
p.dispaly();
return 0;
}


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