Can conversion functions be non-member functions

徘徊边缘 提交于 2019-12-23 13:08:55

问题


Is it possible to define the casting operator from one type to another type outside of the class definition as a non-member function? I know it is possible for other operators like operator- but It is not possible with cast operators. For example for two classes A and B, I tried to define the casting operator outside of the A and B scopes as follows:

operator A(const B& b)
{
    A a(....);
    return a;
}

回答1:


No, conversion functions must be member functions.

From C++11, [class.conv.fct]/1:

A member function of a class X having no parameters with a name of the form [operator conversion-type-id] specifies a conversion from X to the type specified by the conversion-type-id. Such functions are called conversion functions.

There are no other conversion functions, in particular there are no non-member conversion functions.




回答2:


Conversion operators are specific to class i.e they provide a means to convert your-defined type to some other type. So, they must be the member of a class for which they are serving purpose :-

for e.g:-

class Rational
{
  public:
     operator double ();
};

Here operator double provide a means to convert Rational object to double.



来源:https://stackoverflow.com/questions/26994485/can-conversion-functions-be-non-member-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!