c ++使用const参数而不是非常量参数覆盖虚函数

c++ override virtual function with const parameter instead of non-const parameter

当我写一个const参数而不是非常量参数的覆盖函数时,我以为编译器会报错,因为基函数有非常量参数,但它编译成功了。为什么?

我的代码:

#include <iostream>

class A
{
public:
    virtual uint64_t cal(uint64_t value)
    {
        std::cout << value << std::endl;
        return value;
    }
};
class B : public A
{
public:
    uint64_t cal(const uint64_t value) override;
};
uint64_t B::cal(const uint64_t value)
{
  std::cout << value + 1 << std::endl; 
  return (value+1);
}
int main()
{
    B b;
    b.cal(1);
    return 0;
}

请注意,考虑函数类型时会删除顶级 cv 限定符,因此 uint64_t cal(uint64_t)uint64_t cal(const uint64_t) 被视为相同的 function type

(强调我的)

The type of each function parameter in the parameter list is determined according to the following rules:

4) Top-level cv-qualifiers are dropped from the parameter type (This adjustment only affects the function type, but doesn't modify the property of the parameter: int f(const int p, decltype(p)*); and int f(int, const int*); declare the same function)

Why?

因为函数参数的顶部 const 限定符在声明中被忽略。

uint64_t cal(uint64_t value);

uint64_t cal(const uint64_t value);

声明完全相同类型的函数。 cal 是一个接受 uint64_t 并返回 uint64_t 的函数。 const 限定符对调用代码没有影响,因为 value 始终是传入参数的 copy

唯一的区别在于函数体,其中 const 限定符将阻止您修改参数。但这是一个实现细节。

这种差异甚至会引发编码风格问题。例如见

顶级 const 参数不是函数签名的一部分。重载的唯一要求是签名必须匹配。

#include <type_traits>

int main()
{
  static_assert(std::is_same_v<int(int), int(const int)>);
}

Compiles fine