1. 程式人生 > >運算子過載:複數類

運算子過載:複數類

運算子的過載:

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;