リロードされたオペレータメンバー関数と非メンバー関数

1818 ワード

今日effective STL第26条の条項を見ていると、自分が意識していなかったことに気づきました(自分のc++の基礎はやはりスラグレベルo(′□╰)o).
クラスがオペレータを再ロードする場合、同じオペレータが全ローカル領域に再ロードされると、オペレータが呼び出されると選択の問題に直面します.
そこで自分でtestしてみると,同じ条件下でクラス内のオペレータリロード関数を優先的に選択することが分かった.(考えてみれば合理的)
クラスのメンバー関数としては、リロード関数の選択が優先されるため、リロード関数を呼び出すときにコンパイラがどのリロード関数を選択できない場合があることに注意してください.
以下はtestコードです.
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

class A{
public:
	A(int value){
		v = value;
	}
	int V() const{
		return v;
	}
	bool operator==(const A &x){
		cout << "member function called!" << endl;
		return v==x.V();
	}
private:
	int v;
};

class B{
public:
	B(int value){
		v = value;
	}
	int V()const{
		return v;
	}
	bool operator==(const A &x){
		cout << "member function of B called" << endl;
		return v==x.V();
	}
private:
	int v;
};


class C{
public:
	C(int value){
		v = value;
	}	
	int V() const {
		return v;
	}
	bool operator==(const int &x){
		cout << "member function of C called" << endl;
		return v==x;
	}
private:
	int v;
};

bool operator==(const C &x,const double &y){
	cout << "global function called" << endl;
	return x.V()==y;
}

bool operator==(const C &x,const int &y){
	cout << "global function called" << endl;
	return x.V() == y;
}

bool operator==(const A &x,const A &y){
	cout << "global function called" << endl;
	return x.V()==y.V();
}

int main(){

	A ta(5);
	A tb(5);
	ta == tb;

	B ca(5);
	ca == ta;//  ==    operator==

	C tc(5);
	/*
	const double tmp = 5;
	tc==tmp;
	    ,              C  ==      ==
	*/