對於c++中流操作符重載的理解

對於IO成員函數的重載不應該是一個成員函數的方式,並且應該聲明爲友元


一、如果爲成員函數,都會有一個某人的參數,也就是this指針,爲左操作數,下面考慮將其聲明爲成員函數的方式

對於cout<<t<<endl cout爲左操作數,說明cout本身有一個重載的操作符方法,這顯然是不可以的。

對於t<<cout;也是有問題的,因爲更具<<的重載方式

ostream& operator<<(ostream& cout,const Test& t);

其中cout匹配左操作數,t匹配右操作數,在這裏cout就會與t匹配,而t與cout匹配,矛盾


二、應該是一個全局的函數

因爲本身全局函數沒有this指針的問題,所以可以向正常的方式調用

cout<<t<<endl;


最終的實現爲

test.h

#ifndef TEST
#define TEST
#include <iostream>

using namespace std;

class Test{
public:
	Test(int,int);
	ostream& operator<<(ostream&,const Test&);
private:
	int a;
	int b;
};

#endif


test.cpp

#include "test.h"

Test::Test(int a,int b){
	this->a=a;
	this->b=b;
}

ostream& operator<<(ostream& out,const Test& t){
	cout<<t.a<<" "<<t.b<<endl;
}

int main(){
	Test t(1,2);
	cout<<t<<endl;
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章