C++重载运算符

#include<iostream>
#include<iomanip>
#include<string>
using namespace std;

//重载运算符的意义:
//复数类:繁琐的调用,冗余的参数列表
class CComplex{
private:
	int iReal;//实部
	int iImg;//虚部
public:
	CComplex(int real, int img) : iReal(real), iImg(img){}
	void Disp(){cout << "(" << iReal << ", -" << iImg << ")" << endl;}
	//相同:1)均为类的成员函数;2)实现同一功能
	void Add(CComplex& a, CComplex& b){iReal = a.iReal + b.iReal; iImg = a.iImg + b.iImg;}
	CComplex operator+(CComplex& other){
		CComplex oComplex(0,0);
		oComplex.iReal = iReal + other.iReal;
		oComplex.iImg = iImg + other.iImg;
		return oComplex;
	}
	void operator+=(CComplex& other){iReal += other.iReal; iImg += other.iImg;}
};


void ComplexTst()
{
	CComplex a(1,1), b(2,2), c(0,0);
	a.Disp(); b.Disp();
	//c.Add(a, b); c.Disp();
	//c = a + b;c.Disp();//重新解释了加法,可以直接进行类的运算
	c = a.operator+(b); c.Disp();//重新解释了加法,可以直接进行类的运算
	c.operator+=(b); c.Disp();
}

class CStr{
private:
	char* lpszBuff;
	int iCnt;
public:
	CStr(const char* buff){iCnt = strlen(buff); lpszBuff = new char[iCnt+1]; strcpy(lpszBuff, buff);}
	~CStr(){delete [] lpszBuff;}
	void Disp(char* self){cout << self << " : " << lpszBuff << endl;}
	CStr& operator=(CStr& other){
		if(this != &other){
			delete [] lpszBuff;
			iCnt = other.iCnt;
			lpszBuff = new char[iCnt+1];
			strcpy(lpszBuff, other.lpszBuff);
		}
		return *this;
	}
};


void StrTst()
{
	CStr oStr1("Hello"); oStr1.Disp("oStr1");
	CStr oStr2("World"); oStr2.Disp("oStr2");
	//没有重载运算符=造成的问题:
	//1、内存泄漏;	2、对同一个内存块的2次释放;
	oStr2 = oStr1; oStr1.Disp("oStr1"); oStr2.Disp("oStr2");
}


class CArr{
private:
	int IntArr[4];
public:
	CArr(int a, int b, int c, int d){IntArr[0] = a; IntArr[1] = b; IntArr[2] = c; IntArr[3] = d;}
	int& operator[](int idx){//可取值,可赋值
		if(idx < 0){
			cout << "Underflow" << endl; idx = 0;
		}
		else if(idx > 3){
			cout << "Overflow" << endl; idx = 3;
		}
		return IntArr[idx];
	}
	int& operator()(int idx){//可取值,可赋值
		if(idx < 0){
			cout << "Underflow" << endl; idx = 0;
		}
		else if(idx > 3){
			cout << "Overflow" << endl; idx = 3;
		}
		return IntArr[idx];
	}
};


void ArrTst()
{
	CArr oArr(5,2,3,9);
	cout << oArr[0] << endl;
	oArr.operator[](0) = 1;
	cout <<  oArr.operator[](0) << endl;


	cout << oArr(3) << endl;
	oArr.operator()(3) = 4;
	cout << oArr.operator()(3) << endl;

}


void main()
{
	ComplexTst();
	StrTst();
	ArrTst();
}


阅读更多
版权声明:本文为博主原创文章,允许转载,转载请注明出处。 https://blog.csdn.net/KnightOnHourse/article/details/79946875
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭