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;
}
如何实现复数的相加:#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++ 运算符重载 转换函数 第一讲
- [C++学习]矩阵运算符重载
- [转] C++ 运算符重载 转换函数
- C++中运算符重载
- 第八章 C++函数的高级特性(8.3 参数的缺省值 8.4 运算符重载 8.5 函数内联)
- c++ 运算符重载
- C++ 中的运算符重载
- C++编程实例-运算符重载
- C++学习摘要之七:运算符重载
- c++中的运算符重载
- C++-运算符重载
- C++的=运算符重载并非简单内存拷贝
- C++中运算符重载实例
- 老陈学 C++ 序列之一: 运算符重载
- 浅谈C++中运算符重载
- 王老师 C++ 运算符重载 转换函数 第三讲
- C++对象的++,--运算符重载 374-39
- c++中运算符重载遇到的问题
- C++ 运算符重载 一个例子
- C++的运算符重载