C++
运算符重载。
-
+号运算符重载Person operator+(Person &p1, Person &p2){Person temp ; temp.m_A = p1.m_A + p2.m_B; temp.m_B = p1.m_A + p2.m_B; return temp} 重载运算符 operator,调用简化为Person p1,p2; Person p3 = p1 + p2 .调用实质为 p3 = operato+(p1, p2 ).
-
左移运算符重载 。1.链式编程。2.只能用全局函数重载。
ostream & operator<<(ostrea, & cout, Person &p){ cout << "m_A=" << p.m_A << "m_B = "<< p.m_B; return cout; }
-
重载++运算符。1.前置++2.后置++.注意前置递增返回的是引用,后置递增返回的是值。
// 重载左移运算符 ostream& operato << (ostream & cout, MyInteger myint){ cout << myint.m_Num; return cout; } void test01(){ MyInteger myint; cout << ++myint << endl; } // 重载++运算符 MyInteger& operator++(){ m_Num++; return *this; } // int表示占位参数,用来区分前置和后置++,后置递增返回的一定是值,因为用了一个局部变量来储存,再去返回引用会引发错误。 MyInteger operator++(int){ // 先记录当时结果 MyInteger temp = *this; //后递增 m_Num ++; //最后将记录结果返回 return temp; }