在“函数参数"中,通过const类型在派生类中具有函数参数变化的虚拟函数.会打破虚拟机制吗? [英] Virtual functions with varying of function parameters in derived class by const type in "function parameter" will break virtual mechanism?
问题描述
一位C ++专家告诉我们,在派生类中使用const更改函数参数类型将破坏虚拟调用机制.
A C++ guru told that varying the function parameter type with const in derived class, will break the virtual call mechanism.
我尝试了一个简单的程序(原谅非标准代码,纯粹是为了测试而编写的),但事实证明并非如此. 通过const值更改函数参数不会破坏虚拟机制,
I tried a simple program ( forgive for non standard code, written purely for test) , which prove otherwise. The function parameter change by const value will not break the virtual mechanism,
是否有任何原因&指向这种行为的文档?
Is there any reasons & documentation pointing to this behavior?
关于VS 2012编译器的行为&最新的g ++编译器.
Behavior noted with VS 2012 compiler & latest g++ compiler.
#include <iostream>
using namespace std;
class Base
{
public:
Base(){ cout<<"base"<<endl;}
virtual ~Base(){ cout<<"dest base"<<endl;}
virtual void test(const int x){ cout << "base test"<<"x = " << x<<endl;}
};
class Derived : public Base
{
public:
Derived(){ cout<<"derived"<<endl;}
virtual ~Derived(){ cout<<"dest derived"<<endl;}
virtual void test(int x){ cout << "derived test"<<"x = " << x<<endl;}
};
int main() {
Base *b = new Derived();
b->test(10);
delete b;
return 0;
}
输出:
base
derived
derived testx = 10
dest derived
dest base
推荐答案
顶级cv限定词不是函数签名的一部分,只是被忽略了.
The top level cv-qualifier is not part of function signature, they are simply ignored.
生成参数类型列表后,在形成函数类型时会删除所有修改参数类型的顶级cv限定符.
After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type.
这篇关于在“函数参数"中,通过const类型在派生类中具有函数参数变化的虚拟函数.会打破虚拟机制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!