const限定词从纯虚函数中消失 [英] const qualifier disappears from pure virtual function
问题描述
使用gcc版本4.8.2:
Using gcc version 4.8.2:
在编译代码时,我遇到了一个问题,即参数上的const限定词消失了。这是一个示例:
I'm running into an issue where the const qualifier on my parameters is disappearing when I compile my code. Here is an example:
main.cc:
#include <iostream>
class Base
{
public:
virtual int getSum( const int number ) = 0;
};
class Derived : public Base
{
public:
Derived( const int& num )
: _myNumber( num )
{}
virtual int getSum( const int number )
{
return _myNumber + number;
}
private:
int _myNumber;
};
int main( int argc, const char* argv[] )
{
Base *b = new Derived( 2 );
std::cout << b->getSum( 3 ) << "\n";
}
像这样编译:
g++ main.cc -o const_test
当我运行nm时:
nm const_test | c++filt | grep getSum
我得到以下输出:
0000000000400b60 W Derived::getSum(int)
为什么const在编译时会从函数中消失吗?
Why does the const disappear from my function when it compiles?
推荐答案
您的函数签名
virtual int getSum(const int number) = 0;
实际上完全等于
virtual int getSum(int number) = 0;
const
不影响函数签名声明按值传递的参数。
const
has no effect on the function signature declaration for parameters passed by value.
唯一的效果是,您无法在此方法的潜在定义内更改堆栈上的参数实例。实际上,仅将其放在此处就足够了,以防止在函数主体中更改参数的实例。
The only effect is, that you can't change the parameter instance on the stack inside of a potential definition of this method. It's in fact sufficient to put it only there, to prevent changing the parameter's instance in the function body.
这篇关于const限定词从纯虚函数中消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!