对象继承时重载方法的覆盖问题

来源:互联网 发布:ios修改游戏数据 编辑:程序博客网 时间:2024/05/26 05:51

例子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!

}

这个例子更好的说明了上述观点。

 

原创粉丝点击