test

C++DAY06

01. 复习

各种重载:

  1.1 指针运算符重载
  1.2 复制运算符重载

02. 其他运算符重载

 2.1 逻辑运算符重载
  == != >= <=

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

class Person{
public:
	Person(string name, int age):m_Name(name), m_Age(age){}
	
	bool operator==(Person &p)
	{
		if(this->m_Name == p.m_Name && this->m_Age == p.m_Age)
			return true;
		return false;
	}
	
private:
	string m_Name;
	int m_Age;
};

void test01()
{
	Person p1("Tom", 10);
	Person p2("Tom", 10);
	
	if(p1 == p2)
		cout << "p1 和 p2相等" << endl;
	else
		cout << "p1 和 p2不等" << endl;
}

int main(void)
{
	test01();
	
	return 0;
}

 2.2 函数调用运算符重载

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

class MyPrint{
public:
	void operator()(string text)
	{
		cout << text << endl;
	}
};

void test01()
{
	MyPrint myprint;
	myprint("hello world!");
}

class MyAdd{
public:
	int operator()(int v1, int v2)
	{
		return v1+v2;
	}

};

void test02()
{
	MyAdd myadd;
	//cout<<myadd(1, 2)<<endl; 
	cout<<MyAdd()(1, 2)<<endl; //匿名对象
}

int main(void)
{
	//test01();
	test02();
	
	return 0;
}
posted @ 2019-06-23 16:11  鸿蒙过客  阅读(102)  评论(0编辑  收藏  举报