Unclear use of operator double()

后端 未结 3 1903
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 09:34

I have a Rectangle class with conversion operators to both double and std::string:

class Rectangle
{
public:
    Rectangle         


        
3条回答
  •  误落风尘
    2021-02-07 10:28

    You do not have an operator to output the rectangle to the stream. cout does have an overload that takes a double and your class can be implicitly converted to a double so that is chosen.

    The reason the string overload is not selected and is not considered as an ambiguity is because operator << for a string is a member function and is not included in the member overload and non member overload set of cout. If we comment out the operator double we can see we get a compiler error.

    If we want to have the operator string called then we would need to explicitly cast r into a string. Live Example

提交回复
热议问题