派生带/不带参数的基类函数
Derive base class function with/without arguments
下面的代码有什么问题?
class B
{
public:
int test()
{
cout<<"B:test()"<<endl;
return 0;
}
int test(int i)
{
cout<<"B test(int i)"<<endl;
return 0;
}
};
class D: public B
{
public:
int test(char x) { cout<<"D test"<<endl; return 0; }
};
int main()
{
D d;
d.test();
return 0;
}
问题是名称隐藏。派生类中的函数test()
D
在基类B
中隐藏了test()
的重载,因此表达式中的重载解析不会考虑这些重载:
d.test()
只需添加一个using
声明:
class D: public B
{
public:
using B::test;
// ^^^^^^^^^^^^^^
int test(char x) { cout<<"D test"<<endl;}
};
另请注意,基类B
中的test()
重载应该返回一个int
,但它们不返回任何内容。
根据 C++11 标准的第 6.6.3/2 段,从值返回函数的末尾掉下来而不返回任何内容是未定义的行为。
这是一个教科书式的隐藏案例
d.test();
将不起作用,因为派生类test(char)
隐藏了所有基类函数,如果执行上述操作,则不会调用匹配函数。
相关文章:
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 将自定义函数传递到基抽象类中以延迟执行
- 调用原子的 store() 时可以调用基类型类的函数吗?C++
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 从基类调用函数的多态性
- 在成员构造函数之后调用基类构造函数
- 在C++单元测试上下文中,抽象基类是否应将其他抽象基类作为函数参数
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- 如何在具有相同函数名称的派生类中调用基类的函数
- 我不能访问基类的函数
- 根据模板参数引用不同基类的函数
- 在基/派生类中调用C++的纯虚函数
- C++ 模板化基类的函数模板专用化
- 如果基类指针无法访问派生类成员函数,那么多态性有什么方便的呢?
- 如何在C++中调用基类虚函数
- 指向从指针派生类成员函数的指针,指向基类成员函数
- C++:在共享对象中调用抽象基类构造函数/未定义的符号
- 如何在 C++ 中将参数传递给基类构造函数