C++学习笔记----重载运算符

运算符重载

运算符重载可以在通过成员函数或者全局函数进行重载,编译器提供了内置的运算符;
我们可以通过定义对应的函数和参数进行重载,也可以使用编译器提供的名称`operator运算符()`进行重载;
运算符重载本质是对内置的运算符函数进行重载:函数相同,参数不同;
返回引用和地址需要思考是否导致悬垂引用和悬垂指针,返回值需要思考返回的是值的拷贝带来的影响;
在进行拷贝的时候,需要思考浅拷贝和深拷贝带来的影响,以及深拷贝后内存的管理

class opO{
public:
	//构造函数
	opO(){	}
	opO(int a, int b, int age) : mA(a),mB(b),mAge(new int(age)){	}
	opO(int a, int b) : mA(a),mB(b){ }
	opO(int age) : mAge(new int(age)){	}
	/*注意:本质调用: o.operator+(o1); =>简化调用:o+o1
	opO operator+(opO &o)
	{
		opO temp;
		temp.mA = this->mA + o.mA;
		temp.mB = this->mB + o.mB;
		return temp;
	}
	*/
	//o.operator<<(cout); => o<<cout;
	//成员函数 重载<< 无法实现 cout在左侧,只能使用全局函数
	void operator<<(ostream& cout){	}
	//前置递增必须返回引用,返回值的话是值拷贝;
	opO& operator++()
	{
		mA++;
		return *this;
	}
	// 后置递增必须返回值,返回引用会导致悬垂引用;
	//int占位参数,用于区分前置和后置递增
	opO operator++(int)
	{
		//后置递增
		opO temp = *this;
		mA++;
		return temp;
		
	}
	opO& operator--()
	{
		mB--;
		return *this;
	}
	opO operator--(int)
	{
		opO temp = *this;
		mB--;
		return temp;
	}
	//析构函数,在使用无参构造器未初始化指针,然后析构会发生未定行为
	~opO()
	{
		if(NULL != mAge)
		{
			delete mAge;
			mAge = NULL;
		}
	}
	// 编译器提供的四个默认函数,无参构造、拷贝构造、析构、赋值运算符重载
	//拷贝构造、赋值运算符重载是浅拷贝,对于堆区开辟数据需要自己实现深拷贝
	opO& operator=(opO& o)
	{
		mA = o.mA;
		mB = o.mB;
		if(mAge != NULL)
		{
			delete mAge;
			mAge = NULL;
		}
		mAge = new int(*o.mAge);
		//局部对象返回只能是值传递拷贝方式,
		//局部对象的引用和指针不能返回,会导致悬垂引用		
		return *this;
	}
	bool operator==(opO& o)
	{
		if(this->mA == o.mA && this->mB == o.mB && *this->mAge == *o.mAge)
		{
			return true;
		}else 
			return false;
	}
	bool operator!=(opO& o)
	{
		if(this->mA != o.mA || this->mB != o.mB || *this->mAge != *o.mAge)
		{
			return true;
		}else
			return false;
	}
  //仿函数
	void operator()(const string& s)
	{
		cout<<"s: "<<s<<endl;
	}
	int operator()(int num1, int num2)
	{
		int sum = num1 + num2;
		return sum ;
	}
	
	
	int* mAge;
private:
	int mA;
	int mB;
	//如果私有变量不想写get和set获取,可以使用友元
	friend opO operator+(opO& o1, opO& o2);
	friend ostream& operator<<(ostream& out, const opO& o);
}; 
// 本质调用 o = operator+(o1,o2) => o = o1 + o2
opO operator+(opO& o1, opO& o2)
{
	opO temp;
	temp.mA = o1.mA + o2.mA;
	temp.mB = o1.mB + o2.mB;
	return temp;
}
//链式编程思想,需要返回对应可以调用该方法的对象引用
ostream& operator<<(ostream& out, const opO& o)
{
	cout<<"mA: "<<o.mA<<" mB: "<<o.mB;
	return out;
}
void test01()
{
opO o1;

cout<<++(++o1)<<endl
	<<o1<<endl;
cout<<--(--o1)<<endl
	<<o1<<endl;
cout<<o1++<<endl
	<<o1<<endl
	<<o1--<<endl
	<<o1<<endl;
}
void test02()
{
	opO o1(18,19,20);
	opO o2(20,19,20);
	opO o3(18,19,20);
	bool a = o1 == o2 ? 1 : 0;
	bool b = o1 == o3 ? 1 : 0;
	bool c = o3 == o2 ? 1 : 0;
	cout<<"oo.a: "<<a<<endl;
	cout<<"oo.b: "<<b<<endl;
	cout<<"oo.c: "<<c<<endl;
}
void test03()
{
	opO o1;
	o1("string hhh");
	int res = o1(1, 2);
	cout<<"res: "<<res<<endl;
	cout<<(opO()(1,2))<<endl;
}

int main()

{
	test03();
	system("pause");
	return 0;
}

posted @ 2024-06-22 17:08  万舜  阅读(8)  评论(0编辑  收藏  举报