gpt4 book ai didi

c++ - 我对 C++ 中的类覆盖有疑问

转载 作者:行者123 更新时间:2023-12-05 01:22:11 25 4
gpt4 key购买 nike

当我研究override关键字时,我发现了一些奇怪的东西,比如下面的代码。

#include <iostream>
template <class T>
class A
{
public:
virtual void some_function(const T a)
{
std::cout<<__PRETTY_FUNCTION__<<std::endl;
std::cout<<"Base"<<std::endl;
}
};
class Derived : public A<int*>
{
public:
virtual void some_function(const int* a)
{
std::cout<<__PRETTY_FUNCTION__<<std::endl;
std::cout<<"Derived"<<std::endl;
}
};
int main()
{
A<int*>* p = new Derived;
p->some_function(nullptr);

delete p;
}

当我第一次看到该代码时,我希望调用 “Derived”。但是上面的代码打印结果如下。

void A<T>::some_function(T) [with T = int*]

Base

但是当我在 Derived 类中的 some_function 中删除 const 关键字时,

class Derived : public A<int*>
{
public:
virtual void some_function(int* a)
{
std::cout<<__PRETTY_FUNCTION__<<std::endl;
std::cout<<"Derived"<<std::endl;
}
};

它打印“Derived”。你能告诉我为什么会这样吗?

最佳答案

函数原型(prototype)不一样。对于 T=int* const T a : aconst指向 int 的指针, 而 const int *a是指向 const int 的指针.其中一个指针是 const , 对于另一个 intconst .

int * const a将与 const T a 相同, 或者你可以制作 T=const int* .

https://godbolt.org/z/WEaEoGh58

同样重要的是要注意:当您从 class 派生时你必须声明 virtual析构函数。

提示:当您使用关键字 override 时在派生函数上,你会得到一个错误,表明你没有覆盖函数:https://godbolt.org/z/o87GMrhsd

关于c++ - 我对 C++ 中的类覆盖有疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74430850/

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