重载的操作符成员函数与非成员函数

时间:2021-11-10 17:48:54

今天看effective STL第26条条款时,发现自己之前没意识到如下的几点(看来自己的c++基础还是渣渣水平o(╯□╰)o)。

如果一个类重载操作符,当在全局域内也重载了同样的操作符,那么在调用该操作符时会面临选择问题。

于是自己test了一下,发现在同等条件下,优先选择类中的操作符重载函数。(想想也挺合理的)

作为类的成员函数这一点在进行重载函数选择时是一个优先的,因此注意某些情况会导致调用重载函数时编译器无法抉择哪一个重载函数。

以下是test代码:

#include <iostream>
#include <list>
#include <stack>
#include <vector>
#include <deque>
#include <queue>
#include <algorithm>
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中的==还是全局中的==
	*/<( ̄ˇ ̄)/
	const int tmp = 5;
	tc==tmp;//输出member function of C called

	system("pause");
	return 0;
}