gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:15:51 24 4
gpt4 key购买 nike

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

我的代码:

#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;
}

最佳答案

Why?



因为函数参数的顶部 const 限定符在声明中被忽略。
uint64_t cal(uint64_t value);


uint64_t cal(const uint64_t value);

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

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

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

Is it better to remove "const" in front of "primitive" types used as function parameters in the header?

关于c++用const参数而不是非常量参数覆盖虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60520805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com