重载运算符操作_学习

时间:2023-02-04 17:33:44
//A:  操作符重载实现为类成员函数
/*
#include <iostream>
class Person
{
private:
	int age;
public:
	Person(int a){
	    this->age=a;
	}
	//inline bool operator==(const Person &ps)const;
	inline bool operator==(const Person *ps)const;
};
//inline bool Person::operator==(const Person &ps)const{
//	std::cout<<"this->age=="<<this->age<<",  ps.age=="<<ps.age<<"\n";
//	if(this->age == ps.age)
//		return true;
//	else
//		return false;
//};
inline bool Person::operator==(const Person *ps)const{
	std::cout<<"this->age=="<<this->age<<",  ps->age=="<<ps->age<<"\n";
	if(this->age == ps->age)
		return true;
	else
		return false;
};

int main()
{
     //Person p1(10);
	 //Person p2(10);
	 Person *a = new Person(10);
	 Person *b =  new Person(10);

	 //if(p1 == p2)
	 if(a == b)
	 {
	     std::cout<<"相等\n";
	 }else
		 std::cout<<"不相等\n";
     system("pause");
	 return 0;
	 //由上面的测试可以得出结论,指针与指针之间是不能进行重载运算符比较的
}*/

//B:操作符重载实现为非类成员函数(全局函数)
#include <iostream>
using namespace std;
class Person
{
public:
	int age;
};
bool operator==(Person const &p1, Person const &p2)
{
	if(p1.age == p2.age)
		return true;
	else
		return false;
};

class Test
{
private:
	int m_value;
public:
	Test(int x=3){ m_value = x; }
	Test &operator++(); //前增量
	Test &operator++(int);//后增量
	void display()
	{
	  cout<<"m_value="<<m_value<<"\n";
	}
};

//前增量 Test& 是指返回一个Test的地址
Test& Test::operator++(){
    m_value++; //先增量
	return *this; //返回当前对像
};

//后增量
Test& Test::operator++(int)
{
    Test tmp(*this); //创建临时对像
	m_value++; //再增量
	return tmp; //返回临时对像
}


int main()
{
	Person a;
	Person b;
	a.age=10;
	b.age=10;
	if(a == b){
	    cout<<"相等\n";
	}else
		cout<<"不相等\n";
	cout<<"进行另外一个测试\n";
	Test t;
	t.display();
	t++;
	t.display();
	++t;
	t.display();

    system("pause");
	return 0;
}