文章目录
- 1.函数调用运算符重载
 - 2.强制类型转换运算符重载
 - 2.1对运算符的认识
 - 2.2类型强制转换运算符
 
1.函数调用运算符重载
class Display
{
public:
	void operator()(string text)
	{
		cout << text << endl;
	}
};
class Add
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};
int main() 
{
	Display Print;
	Print("hello world");
	Add add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;
	//匿名对象调用  
	cout << "Add()(100,100) = " << Add()(100, 100) << endl;
	return 0;
}
 

2.强制类型转换运算符重载
2.1对运算符的认识
C++ 中类型的名字/类的名字本身是一种类型强制转换运算符
2.2类型强制转换运算符
- 单目运算符
 - 可以被重载为成员函数[不能被重载为全局函数]
 
重载
int类型强制转换运算符
class Test
{
public:
	Test(int a = 0, int b = 0) 
		:_a(a)
		, _b(b) 
	{
	}
	//重载 强制类型转换运算符时 
	// 返回值类型是确定的 
	// 即运算符本身代表的类型
	// 不需要指定返回值类型
	operator int()
	{ 
		return _a; 
	}
private:
	int _a;
	int _b;
};
int main()
{
	Test obj(10, 20);
	//obj.operator int()
	cout << (int)obj << endl;  //10
	//类A如果对int进行了  强制类型转换运算符重载
	//那么类A的对象参与含int这个类型的表达式时 
	//该类A的对象就会调用operator int() 
	// 即类A的对象一旦出现在含int这个类型的表达式时
	// 这个对象在此处的值就是调用operator int()这个函数的返回值
	int n = 5 + obj;           //int n = 5 + obj.operator int()
	cout << n << endl;         //15
}
                


















