#include "stdafx.h"
#include <iostream>
//
//函数重载
//
namespace operator_test
{
//
//先定义一个类
//
class CObject
{
public:
CObject(int a) : m_a(a)
{
}
int Get()
{
return m_a;
}
int Add(CObject& obj2)
{
return (this->Get() + obj2.Get());
}
int operator+(CObject& obj2)
{
return (this->Get() + obj2.Get());
}
private:
int m_a;
};
int Add(CObject& obj1, CObject& Obj2)
{
return (obj1.Get() + Obj2.Get());
}
//int operator+(CObject& obj1, CObject& Obj2)
//{
// return (obj1.Get() + Obj2.Get());
//}
}
void test_operator_test()
{
operator_test::CObject obj1(10);
operator_test::CObject obj2(20);
//
//1 把obj1 和 obj2相加,相加后的值. 通过一个全局函数来实现
//
std::cout << operator_test::Add(obj1, obj2) << std::endl;
//
//1 把obj1 和 obj2相加,相加后的值. 通过CObject一个函数来实现
//
std::cout << obj1.Add(obj2) << std::endl;
//
//1 把obj1 和 obj2相加,相加后的值. 把obj1.Add变得更可读
//
std::cout << (obj1 + obj2) << std::endl;
std::cout << obj1.operator+(obj2) << std::endl; //跟上面语句是等价的.
//
//所以std::cout也可以写成下面的样子
//
std::cout.operator<<(obj1.operator+(obj2))<< std::endl;
}
//
//双目运算符,类成员情况下。classobject1.operator x (classobject2) 等价于 classobject1 x classobject2
//