转换函数可以是非成员函数吗 [英] Can conversion functions be non-member functions

查看:128
本文介绍了转换函数可以是非成员函数吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将类定义之外的一种类型的转换运算符定义为非成员函数?我知道像操作符这样的其他操作符也是可能的,但是使用强制转换操作符是不可能的.例如,对于两个类A和B,我试图在A和B范围之外定义转换运算符,如下所示:

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;
}

推荐答案

否,转换函数必须是成员函数.

No, conversion functions must be member functions.

从C ++ 11开始,[class.conv.fct]/1:

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

X成员函数,该类不带名称为[operator conversion-type-id ]形式的参数,表示从X转换为 conversion-type-id 指定的类型.这些功能称为转换功能.

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.

这篇关于转换函数可以是非成员函数吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆