C++ Primer 5th notes (chap 14 overloaded operations and type conversion) function matching and overloaded operators

If a class provides both a type conversion whose conversion target is an arithmetic type and an overloaded operator, it will encounter the ambiguity between the overloaded operator and the built-in operator.

If a is a type, the expression a sym b may be:
//The call form cannot be used to distinguish whether the current call is a member function or a non-member function
a.operatorsym(b); //a has an operatorym member function
operatorym( a,b); //operatorsym is an ordinary function

eg.


class SmallInt{
    
    
	friend SmallInt operator + (const SmallInt&,const SmallInt&);
public:
	SmallInt(int = 0);
	operator int() const {
    
    return val;}
private:
	std::size_t val;
};

SmallInt s1,s2;
SmallInt s3 = s1 + s2;	//使用重载的 operator+
//二义性错误,可以把0转换成 SmallInt,然使用 SmallInt 的 +;
//或者把 s3 转换成 int,然后对于两个 int 执行内置的加法。
int i = s3 + 0;		
  • The set of candidate functions for operators in expressions includes both member functions and non-member functions.
  • When an overloaded operator is used to act on an object of a class type, the candidate function contains the ordinary non-member version and the built-in version of the operator. In addition, if the operand on the left is a class type, the overloaded version of the operator defined in the class is also included in the candidate function.

[Quote]

[1] Code classTypeExchange.h

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/114210728