zoukankan      html  css  js  c++  java
  • 【转】C++中继承中的同名成员问题

    C++中,子类若有与父类同名的成员变量和成员函数,则同名的成员变量相互独立,但同名的子类成员函数重载父类的同名成员函数。举例如下:

    #include <iostream>
    
    using namespace std;
    
    class A{
    public:
        int a;
        A(){
            a = 1;
        }
        
        int get_a(){
            return a;
        }
    
        void print(){
            cout << "This is A. a: " << a << endl;
        }
    };
    
    class B: public A{
    public:
        int a;
        B(){
            a = 2;
        }
    
        void print(){
            cout << "This is B. a: " << a << endl;
        }
    };
    
    int main(){
        A test1;
        B test2;
    
        cout << "test1.a: " << test1.get_a() << endl;
        test1.print();
        cout << "test2.a: " << test2.get_a() << endl;
        test2.print();
        return 0;
    }
    

     输出结果为:

    test1.a: 1
    This is A. a: 1
    test2.a: 1
    This is B. a: 2
    

     为什么test2.get_a()中得到的a值为1而非2呢?这是因为类B中没有get_a()这个函数,所以去其父类中找。找到这个函数后,依就近原则,把类A中的a给取了出来。而test2.print()调用的是类B中的print()函数,依就近原则,把类B中的a取了出来。这也就说明了,同名的成员变量相互独立,而同名的成员函数会发生覆盖。

  • 相关阅读:
    洛谷P3275 [SCOI2011]糖果
    2018年12月30&31日
    洛谷P4114 Qtree1
    洛谷P4116 Qtree3
    洛谷P4315 月下“毛景树”
    洛谷P1505 [国家集训队]旅游
    洛谷P2253 好一个一中腰鼓!
    CF616D Longest k-Good Segment
    洛谷P3979 遥远的国度
    洛谷P2486 [SDOI2011]染色
  • 原文地址:https://www.cnblogs.com/sunada2005/p/3396763.html
Copyright © 2011-2022 走看看