C++虚拟析构函数
创建原型类时,我这样布置析构函数:
virtual ~MyClass();
当在库中完成该类时,我注意到我无法添加“虚拟”。这是正常的吗?是否考虑到了虚拟因素,或者我做错了什么?
例如;当我尝试这样做时,我收到编译器错误:
virtual MyClass::~MyClass() { }
相反,这样做有效:
MyClass::~MyClass() { }
我的问题是,因为我不必在析构函数的最终代码写入中包含 virtual
,析构函数仍然表现为虚拟析构函数(因为它是虚拟的原型)?
When creating prototype classes I lay out the destructor as such:
virtual ~MyClass();
When finalizing the class in a library I noticed that I cannot add 'virtual'. Is this normal, and is virtual taken into consideration or am I do something wrong?
For example; when I try to do this I get a compiler error:
virtual MyClass::~MyClass() { }
Instead doing this works:
MyClass::~MyClass() { }
My question is since I do not have to include virtual
in the final code write of the destructor does the destructor still behave as a virtual destructor (since it is virtual as a prototype)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
virtual 关键字只能用于类声明中的函数声明(通常在头文件中),而不能用于源文件中的定义。对于所有函数都是如此,而不仅仅是析构函数。
The virtual keyword can only be used on the function declarations within a class declaration (typically in a header file), not on the definitions within a source file. This is true for all functions, not just destructors.
virtual 关键字仅用作类定义内部成员函数声明的一部分。
如果成员函数是在类定义之外定义的,则
virtual
关键字不会放置在那里。The
virtual
keyword is only used as part of the member function declaration inside of the class definition.If the member function is defined outside of the class definition, the
virtual
keyword is not placed there.