对象赋值-赋值运算符重载
赋值运算符函数是在类中定义的特殊的成员函数
典型的实现方式:
ClassName& operator=(const ClassName &right) { if (this != &right) {
//将right的内容复制给当前的对象
} return *this; }
#include <iostream> using namespace std; class Test { int id; public: Test(int i) :id(i) { cout << "obj_" << id << "created\n"; } Test& operator= (const Test& right) { if (this == &right) cout << "same obj!" << endl; else { cout << "obj_" << id << "=obj_" << right.id << endl; this->id = right.id; } return *this; } }; int main() { Test a(1), b(2); cout << "a = a:"; a = a; cout << "a = b:"; a = b; return 0; }
流运算符重载函数的声明
istream& operator>>(istream& in, Test& dst);
ostream& operator<<(ostream& out, const Test& src);
备注:
函数名为:
operaotor>>和operator<<
返回值为:
istream& 和ostream&,均为引用
参数分别:流对象的引用,目标对象的引用。对于输出流,目标对象还是常量
#include <iostream> using namespace std; class Test { int id; public: Test(int i) :id(i) { cout << "obj_" << id << "created\n"; } friend istream& operator >> (istream& in, Test& dst); friend ostream& operator << (ostream& out, const Test& src); }; //备注:以下两个流运算符重载函数可以直接访问私有成员,原因是其被声明成了友元函数 istream& operator >> (istream& in, Test& dst) { in >> dst.id; return in; } ostream& operator << (ostream& out, const Test& src) { out << src.id << endl; return out; } int main() { Test obj(1); cout << obj; cin >> obj; cout << obj; }
怕什么真理无穷,进一寸有一寸的欢喜。---胡适