运算符的重载:
1,只能重载已存在的运算符
2,自定义类型和内置满足的相同的逻辑
1.普通运算符可以重载
2.类型重载
const :
1、防止实参被修改;
2、接收隐式生成临时对象;
类内是this_call的调用约定,成员方法隐藏this指针,指向一般为左操作数,所以只用传右操作数即可
代码如下:
class CComplex
{
public:
CComplex(int real, int img) :mreal(real), mimg(img){} //构造
类内实现+的重载 右操作数类型为int
const CComplex operator+(int rhs)
{
std::cout << "CComplex::operator+(int)" << std::endl;
return CComplex(mreal + rhs, mimg);
}
CComplex cc2 = cc1 + 10; //cc1.operator+(10);
//类内实现<<的重载
//std::ostream& operator<<(std::ostream& out)
//{
// out << mreal << " ";
// out << mimg << " ";
// return out;
//}
//cc1 << std::cout;左操作数是类内的对象
private:
int mreal; //实部
int mimg; //虚部
//类外不能访问类内的私有成员变量,设置友元函数
friend const CComplex operator+(int, const CComplex&);
friend const CComplex operator+(const CComplex&, const CComplex&);
friend std::ostream& operator <<(std::ostream&, const CComplex&);
};
类外是cd_call的调用约定,无this指针,需传两个对象
//类外实现+的重载 左操作数类型为int,右操作数类型为CComplex
const CComplex operator+(int lhs, const CComplex& rhs)
{
std::cout << "global::operator+(int,CComplex)" << std::endl;
return CComplex(lhs + rhs.mreal, rhs.mimg);
}
CComplex cc3 = 10 + cc2; //operator+(10,cc2);
//类外实现+的重载 左操右操作数类型都为CComplex
const CComplex operator+(const CComplex& lhs, const CComplex& rhs)
{
std::cout << "CComplex::operator+(CComplex, CComplex)" << std::endl;
return CComplex(lhs.mreal + rhs.mreal, lhs.mimg + rhs.mimg);
}
CComplex cc4 = cc2 + cc3;
//类外实现<<的重载 左操作数为std::ostream的类型,右操作数为CComplex类型
std::ostream& operator <<(std::ostream& out, const CComplex& rhs)
{
out << rhs.mreal << " ";
out << rhs.mimg << " ";
return out;
}
std::cout << cc1 << std::endl;