C++ 定义到基类的转换 [英] C++ Define Conversion to Base Class
问题描述
我在定义和使用到基类的转换运算符时遇到了困难.考虑以下几点:
I'm having difficulty defining and using a conversion operator to a base class. Consider the following:
class base
{
public:
base(const base&);
base& operator=(const base&);
//some stuff
};
class child : public base
{
public:
operator base() const;
//some more stuff
};
int main()
{
child c;
base b=c;
b=c;
}
如果我尝试将子项转换为基数,则永远不会调用 operator base()
(即使我使转换显式).而是直接调用基类中的复制构造函数或赋值运算符,无需转换.
If I attempt to convert a child to a base, operator base()
is never called (even if I make the conversion explicit). Instead, the copy constructor or assignment operator from the base class is called directly, without a conversion.
当将 child
分配(或复制构造)到 base
时,如何调用 operator base()
?
How can I cause operator base()
to be called when a child
is assigned (or copy-constructed) to a base
?
推荐答案
到基类的转换函数在语法上是合法的,但永远不会被调用.来自标准草案 n3337:
A conversion function to a base class is syntactically legal, but it will never be called. From standard draft n3337:
12.3.2 转换函数 [class.conv.fct] §1
[...] 从来没有使用转换函数来转换一个(可能cv 限定)对象到(可能有 cv 限定)相同的对象类型(或对它的引用),到它的(可能是 cv 限定的)基类类型(或对它的引用),或(可能是 cv 限定的)void.[...]
[...] A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void. [...]
该语言有不同的从派生到基类的转换机制.阅读对象切片.简而言之 - 它会自动为您完成.
The language has got different mechanism for conversions from derived to base. Read about object slicing. To put it simply - it's done automatically for you.
这篇关于C++ 定义到基类的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!