C++子类重写模板父类的函数
因为项目上的框架已经搭建好,想子类重写模板类的函数,中途遇见一点问题,特此记录
#include <iostream>
#include <functional>
// 测试模板类里的函数是否可以被子类重写 是的,可以
template <typename MsgType>
class A{
public:
[[nodiscard]] virtual int get(std::function<void(const MsgType&)> callback){
std::cout<<"a MsgType";
// callback();
return 0;
}
};
template <typename TypeName>
class B:public TypeName{
public:
};
class C:public B< A<int> >{
public:
[[nodiscard]] int get(std::function<void(const int&)> callback) override{
std::cout<<"c msgType";
callback(100);
return 0;
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
A<int>* c = new C();
c->get([](int msg){std::cout<<msg;});
return 0;
}
这个代码的输出是:
Hello, World!
c msgType100
如果std::function<void(const MsgType&)> 与 std::function<void(const int&)> 中参数的引用方式不一致,使用override会编译通不过
本文探讨了如何在C++中,子类重写模板类的函数。通过一个实例展示了当子类(类C)继承自模板类B,而B又继承自模板类A时,成功重写`get`函数的过程。代码运行结果验证了子类能够正确覆盖并执行重写后的函数。当模板参数类型不匹配时,`override`关键字会导致编译错误,强调了类型一致性的重要性。
2455

被折叠的 条评论
为什么被折叠?



