是否可以将类定义之外的从一种类型到另一种类型的转换运算符定义为非成员函数?我知道其他运算符(如 operator-)是可能的,但强制转换运算符是不可能的。例如,对于两个类 A 和 B,我尝试在 A 和 B 范围之外定义转换运算符,如下所示:
operator A(const B& b)
{
A a(....);
return a;
}
最佳答案
不可以,转换函数必须是成员函数。
来自 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. Such functions are called conversion functions.
没有其他转换函数,特别是没有非成员转换函数。
关于c++ - 转换函数可以是非成员函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994485/