【发布时间】:2021-02-07 05:45:15
【问题描述】:
拥有
- 定义虚方法的 BASE 类
- 一个 DERIVED 类,它定义了一个同名但签名不同的虚拟方法
当使用指向 DERIVED 类的指针从另一个类调用时,编译器抱怨它无法在 BASE 类中找到正确的函数。
示例(省略构造函数等):
class BASE {
public: virtual int print(std::vector<double>& values);
};
int BASE::print(std::vector<double>& values){
std::cout << "This is the base class!" << std::endl;
}
class DERIVED : public BASE {
public: void virtual print(int a, int b);
};
void DERIVED::print(int a, int b){
std::cout << "This is the derived class from int-method!" << std::endl;
}
class TEST {
public: void testit();
};
void TEST::testit(){
DERIVED derived;
std::vector<double> a;
derived.print(a);
}
编译器抱怨TEST.cpp:30:17: error: no matching function for call to ‘DERIVED::print(std::vector<double>&)
如何在派生类中重载具有不同签名的虚函数?例如,这对于添加 BASE 类中不可用的功能可能很有用。
【问题讨论】:
-
要覆盖函数,它们需要具有完全相同的签名。
-
我想你的意思是覆盖,而不是超载。您不能覆盖具有不同签名的方法。
-
如果您实际上是指超载,请在问题中包含minimal reproducible example 和完整的错误消息
-
这能回答你的问题吗? stackoverflow.com/questions/11912022/…
-
这些函数都不是公开的,因此
print变体都不能供Test::testit调用。
标签: c++ overriding virtual