【发布时间】:2019-06-19 07:37:24
【问题描述】:
考虑以下示例:
#include <iostream>
#include <string>
class Base {
public:
virtual void func(int a) {}
};
class Derived : public Base {
public:
void func( const int a) override {
}
};
int main()
{
Derived d;
d.func(1);
return 1;
}
我重写了func 方法,但将 const 添加到了参数中,在这种情况下,链接器应该发出错误提示。要么函数没有被覆盖,要么函数参数不应该是 const。
但令我惊讶的是,此代码链接并有效。
您可以找到online example here。
我错过了什么吗?为什么这段代码有效?
虽然类似于Functions with const arguments and Overloading,但它解决了一个不同的问题。那个问题是关于不可能重载基类的方法,而这个问题解决的是能够覆盖派生方法的问题。
【问题讨论】:
-
@dewaffled 不,不是。重载和覆盖是两个不同的东西
-
@lzzy 是的,但是the answer there 也回答了您的问题,并且看起来很清楚,可以在此处重新发布:§13.1 where the Standard.. 参数声明仅在存在或不存在 const 和/ 或 volatile 是等价的。也就是说,忽略每个参数类型的 const 和 volatile 类型说明符
-
@dewaffled 是的,你是对的,答案确实回答了我的问题,但我的问题 不同。
标签: c++