C++で継承された同名メンバーの問題

1349 ワード

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

なぜ?get_a()で得られたa値は2ではなく1ですか?クラスBにget_がないからですa()という関数なので、その親クラスに行って探します.この関数を見つけたら,近似の原則に従ってクラスAのaを取り出した.そしてtest 2.print()はクラスBのprint()関数を呼び出し,近接原則に従ってクラスBのaを取り出した.これは、同じ名前のメンバー変数が互いに独立し、同じ名前のメンバー関数が上書きされることを示しています.