先说左移(<<)操作符,也就是我们常说的输出操作符。 对于自定义类来说,重载左移操作符的方法我们常使用类的友元方式进行操作。
示例代码如下:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include <iostream> using namespace std; class Test { public: Test(int age = 0,char *name = "\0") { Test::age = age; strcpy(Test::name,name); } void outmembers(ostream &out) { out<<"Age:"<<age<<endl<<"Name:"<<this->name<<endl; } friend ostream& operator <<(ostream& ,Test&); protected: int age; char name[50]; }; ostream& operator <<(ostream& out,Test &temp) { temp.outmembers(out); return out; } int main() { Test a(24,"管宁"); cout<<a; system("pause"); }
上例代码中,我们对void outmembers(ostream &out)的参数使用ostream定义主要是为了可以向它传递任何ostream类对象不光是cout也可以是ofstrem或者是ostrstream和ostringstream类对象,做到通用性。
重载运算符,我们知道可以是非成员方式也可以是成员方式的,对于<<来说同样也可以是成员方式,但我十分不推荐这么做,因为对于类的成员函数来说,第一个参数始终是会被隐藏的,而且一定是当前类类型的。
下面的示例代码就是将上面的<<重载函数修改成成员方式的做法:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include <iostream> using namespace std; class Test { public: Test(int age = 0,char *name = "\0") { Test::age = age; strcpy(Test::name,name); } void outmembers(ostream &out) { out<<"Age:"<<age<<endl<<"Name:"<<this->name<<endl; } ostream& operator <<(ostream &out) { this->outmembers(out); return out; } protected: int age; char name[50]; }; int main() { Test a(24,"管宁"); a<<cout; system("pause"); }
从代码实现上,我们将函数修改成了ostream& operator <<(ostream &out),迫不得已将ostream类型的引用参数放到了后面,这是因为,成员方式运算符重载函数第一个参数会被隐藏,而且一定是当前类类型的,这和ostream类型冲突了。由此我们在使用cout输出的时候就必须写成a<<cout;,这样一来代码的可读行就大大降低了,这到底是左移还是右移呢?为此我再一次说明,对于左移和右移运算符的重载是十分不推荐使用成员函数的方式编写的。 |