#include<bits/stdc++.h>
using namespace std;
class Complex{
public:
Complex(double r=0.0,double i=0.0):real(r),imag(i){}
Complex operator+(const Complex &c)const{
return Complex(real+c.real,imag+c.imag);
}
Complex operator-(const Complex &c)const{
return Complex(real-c.real,imag-c.imag);
}
Complex& operator++(){ //前置
real++;imag++;
return *this;
}
Complex operator++(int){
Complex old=*this;
++(*this);
return old;
}
//使用friend是因为该函数需要访问私有成员,如果可以通过get_real()类似函数得到私有成员值,也可以不用friend
friend ostream& operator<<(ostream &out,const Complex &c)/*{
return out<<"("<<c.real<<","<<c.imag<<")"; //里外均可
}*/;
private:
double real,imag;
};
ostream& operator<<(ostream &out,const Complex &c){
return out<<"("<<c.real<<","<<c.imag<<")";
}
//[]重载
template <class T>
T &Array<T>::operator[](int n){
assert(n>=0&&n<size);//#include <cassert>
return list[n];
}
//=重载
template <class T>
Array<T>& operator=(const Array<T> &p){
if(this != &p){
if(size>0&&size!=p.size){
delete[] list;
size=p.size;
list=new T[size];
}
assert(list);
//开始复制
}
return *this;
}
int main(){
Complex c1(5,4),c2(2,3),c3;
cout<<c1<<c2<<c3<<endl;
cout<<c1+2<<endl;
return 0;
}
运算符重载
最新推荐文章于 2024-04-18 01:04:31 发布