运算符重载主要用于自定义的类型的符号计算。简化我们的代码使用。
加法运算符重载:
class OperatorClass {
public:
OperatorClass()
:m_first(0), m_second(0)
{
}
OperatorClass(int first, int second)
:m_first(first), m_second(second)
{
}
OperatorClass operator+(const OperatorClass& other) {
OperatorClass temp;
temp.m_first = this->m_first + other.m_first;
temp.m_second = this->m_second + other.m_second;
return temp;
}
void Print() {
std::cout << m_first << " " << m_second << std::endl;
}
public:
int m_first;
int m_second;
};
输出流运算符重载:
std::ostream& operator<< (std::ostream& st_out, OperatorClass& value ) {
st_out << value.m_first << "." << value.m_second << std::endl;
}
OperatorClass test;
std::cout << test << std::endl;