C++继承时子类定义同名成员变量时的调用继承函数的问题

#include<iostream.h>
class Base
{
public:
    int a;
    Base()
    {
        a=0;
        cout<<"I`m base Begin"<<endl;
    }
    int Print()
    {
        cout<<a<<endl;
        return 1;
    }
    ~Base()
    {
        cout<<"I`m base End"<<endl;
    }

};
class Simple: public Base
{
   public:
       int a;
    Simple()
    {
        a=1;
        cout<<"I`m Simple Begin"<<endl;
    }
    ~Simple()
    {
        cout<<"I`m Simple End"<<endl;
    }
    /*
    print()
    {
        cout<<a<<endl;
    }
    */
};
main()
{
    Simple b;
    b.Print();
    cout<<b.a<<endl;
}

输出结果是0,1。而不是1,1。为什么不同呢?

解释:

        因为在继承的时候,允许子类存在与父类同名的成员变量,但是并不覆盖父类的成员变量,他们同时存在。

        首先在base里面有一个 a 变量,然后在simple里面又有一个 a 变量。在孩子类创建对象时,会先调用父类的构造函数,先为父类的 a 变量初始化,然后调用孩子类的构造函数来初始化自己的变量,因为给孩子类中没有定义print函数,所以会按照就近原则去寻找父类中是否有print函数。恰好父类中有这个函数,于是调用父类的print函数b.print(),而这个函数会调用父类的a变量。

        b.a就就近调用孩子类的a变量。

      按照就近原则调用,如果自己的类中定义了接口就调用自己的,如果没有就去父类、祖父类....... 去找,然后调用。

猜你喜欢

转载自blog.csdn.net/braveyly/article/details/45071451
今日推荐