这不是设计缺陷。很好。
- 只要您不使用动态调度,派生类中的函数将隐藏基类函数,并且将选择派生类中适当的重载函数。(下面示例程序中的前 3 个输出)。
- 在动态调度的情况下,将根据对象的实际类型调用适当的覆盖函数(请记住,覆盖函数是
int
作为参数的函数)(下面示例中的最后 3 个输出)。
考虑示例程序以使其更清晰:
#include<iostream>
class Base
{
public:
virtual double Function(int i) const{std::cout<<"\nIn Base int version";}
};
class SubClass : public Base
{
public:
virtual double Function(int i) const{std::cout<<"\nIn Derived int version";}
double Function(std::string str) const{std::cout<<"\nIn Derived string version";}
double Function(double i) const {std::cout<<"\nIn Derived double version";}
};
int main()
{
SubClass obj;
obj.Function(10);
obj.Function(10.1);
obj.Function("Hello");
Base Bobj;
Bobj.Function(10.2);
Base *ptr = new Base;
ptr->Function(10.5);
Base *ptr2 = new SubClass;
ptr2->Function(10);
ptr2->Function(10.5);
delete ptr;
delete ptr2;
return 0;
}
输出是:
In Derived int version
In Derived double version
In Derived string version
In Base int version
In Base int version
In Derived int version
In Derived int version
请注意最后两个输出。