例子1:
class Base
{
public:
void test(int) { cout<<"Base's test(int)"<<endl; }
void test(double) { cout<<"Base's test(double)"<<endl; }
};
class Derive : public Base
{
public:
void test(int) { cout<<"Derive's test(int)"<<endl; }
};
void main()
{
Derive d;
d.test(1.0); //output: Derive's test(int)
}
在子类中,我们只是重写了方法test(int)。调用子类test方法时,参数是double类型,实际上经过类型隐式转换,调用了子类的test(int)。父类的test(double)在子类中已经隐藏起来。
例子2:
class Base
{
public:
void test(int) { cout<<"Base's test(int)"<<endl; }
void test(string) { cout<<"Base's test(string)"<<endl; }
};
class Derive : public Base
{
public:
void test(int) { cout<<"Derive's test(int)"<<endl; }
};
void main()
{
Derive d;
d.test("Hello Test!"); //Compile Error!
}
这个例子更好的说明了上述观点。