【C++】运算符重载 Operator Overload
生活随笔
收集整理的這篇文章主要介紹了
【C++】运算符重载 Operator Overload
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
運算符重載 Operator Overload
可以為運算符增加一些新的功能
class Point { private:int m_x;int m_y; public:Point(int x, int y) :m_x(x), m_y(y) {}void display() {cout << "(" << m_x << ", " << m_y << ")" << endl;} };-
直接將兩個Point類相加得到新的點
比如Point p3 = p1 + p2;,這樣就要使用運算符重載,因為平常加號兩端不可以是Point類的
為運算符加號’+'增加新的功能,返回一個point。
這樣是把運算符重載函數放在類外面,如果放到里面變成一個成員函數,就只要傳入一個Point對象就可以了,并且也不需要聲明友元函數了。
class Point { private:int m_x;int m_y; public:Point(int x, int y) :m_x(x), m_y(y) {}void display() {cout << "(" << m_x << ", " << m_y << ")" << endl;}// 最左邊的const為了防止返回的Point被賦值 (p1 + p2 = p3是不允許的)// 最右邊的const為了const返回值又可以調用operator+ (但要允許p1 + p2 + p3)const Point operator+(const Point &point) const{return Point(this->m_x + point.m_x, this->m_y + point.m_y);// 或者省略this// return Point(m_x + point.m_x, m_y + point.m_y);} }; int main() {Point p1(10, 20);Point p2(20, 30);p1 + p2;// 相當于 p1.operator+(p2); }所以,全局函數、成員函數都支持運算符重載
返回值最好是個const對象,返回值不允許再被賦值,但加上const之后就不允許連續相加了。所以要再加一個const。
- 再實現一下+=
- 完成-p1的操作(單目運算符)
- 前置++和后置++
-
注意:
-
前置++可以被賦值,后置++不可以
比如:
++a = 20; // 可以 (a++) = 20; // 不可以所以前置++返回是一個對象的引用
后置++返回的是const Point
-
-
左移,實現 cout << p1 << endl;
// 不能寫 void operator<<() // 因為<<不是單目運算符 // 下面這個寫法相當于 // p1 << 10; // p1.operator<<(10) void operator<<(int a) {} // 但我們要實現的是cout << p1 << endl; 傳入point // 它就不能是成員函數,必須是全局函數,所以要將其加入Point的友元函數 // cout也是對象,是ostream對象(output stream) // 如果要實現cout << p1 << p2; // 就要返回cout,這很重要! // 但cout的返回值是不能再被賦值的,可以把這個函數放到private中,這樣就不會再被賦值 ostream &operator<<(ostream &cout, const Point& point) {cout << "(" << point.m_x << ", " << point.m_y << ")";return cout; } -
右移,實現輸入
// input stream -> istream istream &operator>>(istream &cin, Point &point) {cin >> point.m_x;cin >> point.m_y;return cin; } -
調用父類的運算符重載函數
-
運算符重載注意點
-
有些運算符不可以被重載
- 對象成員訪問運算符:.
- 域運算符:::
- 三目運算符:?:
- sizeof
-
有些運算符只能寫在類里面重載為成員函數,比如
- 賦值運算符:=
- 下標運算符:[]
- 函數運算符:()
- 指針訪問運算符:->
-
總結
以上是生活随笔為你收集整理的【C++】运算符重载 Operator Overload的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【C++】智能指针 Smart Poin
- 下一篇: 【C++】 类型转换