下面举个简单的例子介绍重载操做符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
&&
和||
就没有短路特性