刚学了c++的运算符重载,为了方便自己复习,发一篇博客来看,希望各位大神给予指导,感激不尽。
//c++运算符重载的方法提要
#include<iostream>
using namespace std;
istream & operator>>(istream & is,ClassName &obj);
ostream & operator<<(ostream & os,const ClassName &obj);
class ClassName{
//重载 输入输出 >> << 要重载成全局的函数,并且在类中做友元声明。
friend istream & operator>>(istream & is,ClassName &obj);
friend ostream & operator<<(ostream & os,const ClassName &obj);
private:
int *p;
public:
//构造函数:
ClassName(){
p=new int[10];
for(int i=0;i<10;++i){
p[i]=i;
}
}
//拷贝构造函数:
ClassName(const ClassName & obj){
delete []p;
p=new int[10];
for(int i =0;i<10;++i){
p[i]=obj.p[i];
}
}
//析构函数:
~ClassName(){
delete [] p;
}
//重载+ - * / % 定义成全局函数会更灵活,可以做2+ClassObj这样的操作,但是现在就先定义成类方法吧。
ClassName operator+(const ClassName obj); //const 防止修改
ClassName operator-(const ClassName obj);
//就只写加减了其他一样。
//重载 == > < >= <= !=
bool operator==(const ClassName obj);
//其他一样。
//重载() []
//返回类型根据你的private来看
int operator[](int j){
return p[j];
}
//把当前对象当函数使用,得重载()运算符
ClassName operator()(int start,int end,int ln);
//重载= += -= *= /= 这些赋值运算符都必须重载为成员函数。
//用&来使return时不调用拷贝构造函数
ClassName &operator=(const ClassName &obj){
if(this=&obj)return *this;//防止自己复制自己
return *this;
}
//重载++ --
//有前置和后置两种,后置的要给个站位参数
//前置:
ClassName &operator++(){
//your operation
return *this;
}
//后置 :
ClassName &operator++(int x){
ClassName temp; //实现先赋值后做操作。
//operation
return temp;
}
//自定义类型转化函数
//operator 目标类型名() const {}
operator int()const{
//...
return ();//结果为目标类型的表达式
}
};