好的,我正在使用虚函数,重载函数和多重继承。当然,情况并不好。
场景:类base1
具有需要由其子级指定的虚函数。
类derived
来自两个父级base1
和base2
,应使用base2
的现有功能来定义base1
的虚函数。
这没关系,但当然很尴尬。动机是我无法更改类base2
,并且已经大量投入的现有界面具有相同名称的base1
和base2
类函数。这没关系,base1
中没有实现任何内容,它应该只重定向到base2
。
我的问题出现了,因为base2
有几个与所讨论的虚函数同名的重载函数。所有其他重载版本在编译时基本上都是隐藏的。
这是一个小型演示代码。
// this version does not compile, overloaded samenameFunc(int, int) cannot be found in the derived class.
#include <iostream>
using namespace std;
class base1 {
public:
virtual void samenameFunc(int scratch) { cout << "from base1: " << scratch << std::endl; }
};
class base2 {
public:
void samenameFunc(int scratch) { cout << "samenameFunc from base2: " << scratch << std::endl; }
void samenameFunc(int scratch, int foo) { cout << "samenameFunc(2 args) from base2: " << scratch << ", " << foo << std::endl; }
};
class derived : public base1, public base2 {
public:
void samenameFunc(int scratch) { base2::samenameFunc(scratch); }// { cout << "from derived: " << scratch << std::endl; }
};
int main()
{
derived d;
d.samenameFunc(66);
d.samenameFunc(77, 88);
return 0;
}
编译错误:
$ g++ inheritance_overload_tester.cc
inheritance_overload_tester.cc: In function ‘int main()’:
inheritance_overload_tester.cc:26: error: no matching function for call to ‘derived::samenameFunc(int, int)’
inheritance_overload_tester.cc:18: note: candidates are: virtual void derived::samenameFunc(int)
如果重命名的重载samenameFunc(int, int
),我可以按预期编译和运行。但请记住,我实际上无法改变base2。
// this version does compile
#include <iostream>
using namespace std;
class base1 {
public:
virtual void samenameFunc(int scratch) { cout << "from base1: " << scratch << std::endl; }
};
class base2 {
public:
void samenameFunc(int scratch) { cout << "samenameFunc from base2: " << scratch << std::endl; }
void anotherFunc(int scratch, int foo) { cout << "anotherFunc(2 args) from base2: " << scratch << ", " << foo << std::endl; }
};
class derived : public base1, public base2 {
public:
void samenameFunc(int scratch) { base2::samenameFunc(scratch); }// { cout << "from derived: " << scratch << std::endl; }
};
int main()
{
derived d;
d.samenameFunc(66);
d.anotherFunc(77, 88);
return 0;
}
如果在现有的演示文稿中无法修复,有人可以建议使用不同的对象继承模型来解决我的问题吗?
答案 0 :(得分:5)
在derived
类的定义中,您可以添加using声明以使base2
中的函数可见:
using base2::samenameFunc;