[英]Can conversion functions be non-member functions
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:
例如,对于两个类A和B,我尝试在A和B范围之外定义转换运算符,如下所示:
operator A(const B& b)
{
A a(....);
return a;
}
No, conversion functions must be member functions. 不,转换函数必须是成员函数。
From C++11, [class.conv.fct]/1: 从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 fromX
to the type specified by the conversion-type-id .没有带有形式名称[
operator
conversion-type-id ]的参数的类X
成员函数指定从X
到由conversion-type-id指定的类型的转换 。 Such functions are called conversion functions.这些功能称为转换功能。
There are no other conversion functions, in particular there are no non-member conversion functions. 没有其他转换函数,特别是没有非成员转换函数。
Conversion operators are specific to class ie 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 eg:- 例如: -
class Rational
{
public:
operator double ();
};
Here operator double provide a means to convert Rational object to double. 这里operator double提供了将Rational对象转换为double的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.