下面舉個簡單的例子介紹重載操做符ios
#include <iostream> class A { friend std::istream &operator>>(std::istream &, A &); friend std::ostream &operator<<(std::ostream &, const A &); public: A() : num(0) {} A(int n) : num(n) {} A &operator+=(const A &); A operator+(const A&); private: int num; };
這裏定義了一個A類,構造函數有兩個函數
重載操做符須要定義重載函數,與通常函數類似,
重載函數須要有返回值,形參列表。
通常而言,重載操做符的操做元素個數應該與形參列表一致,
本例中由於存在隱含的this
參數,因此少一個。測試
這裏給出+
和+=
的重載函數定義this
A A::operator+(const A&a) { return A(num+a.num); } A &A::operator+=(const A &other) { num += other.num; return *this; }
當友元須要經過操做符來操做對象時,也能夠重載code
std::istream &operator>>(std::istream &in, A &a) { in >> a.num; if (!in) a.num = 0; return in; } std::ostream &operator<<(std::ostream &out, const A &a) { out << a.num; return out; }
經過下面代碼測試功能對象
#include "A.hpp" int main() { A a1; A a2; std::cin >> a1 >> a2; a1 += a2; a1.operator+=(a2); std::cout << a1 << std::endl; std::cout << a1 + a2 << std::endl; return 0; }
重載操做符有幾點須要注意的ci
&&
和||
就沒有短路特性