1

クラス B 初期化リストのメンバーである基本クラス A にアクセスできないのはなぜですか?

   class A
    {
    public:
        explicit A(int a1):a(a1)
        {
        }
        explicit A()
        {
        }

    public:
        int a; 

    public:
        virtual int GetA()
        {
            return a;
        }
    };

    class B : public A
    {
    public:
        explicit B(int a1):a(a1) // wrong!, I have to write a = a1 in {}. or use A(a1)
        {
        }
        int GetA()
        {
            return a+1;
        }
    };

    class C : public A
    {
    public:
        explicit C(int a1):a(a1)
        {
        }
        int GetA()
        {
            return a-1;
        }
    };
4

3 に答える 3

6

Alexの回答に基づいて構築するには、次のように、その構造を制御することにより、基本クラスの「a」メンバーを初期化できます。

class B : public A
{
public:
    explicit B(int a1) : A(a1) { }  // This initializes your inherited "a"
    ...
};

継承されたメンバー(小文字の「a」 、例から引用)を直接初期化しようとするのではなく、上記の基本クラス(大文字の「A」 )を構築していることに注意してください。

于 2009-08-20T04:35:35.137 に答える
6

A's constructor runs before B's, and, implicitly or explicitly, the former construct all of A's instance, including the a member. Therefore B cannot use a constructor on a, because that field is already constructed. The notation you're trying to use indicates exactly to use a constructor on a, and at that point it's just impossible.

于 2009-08-20T04:10:14.233 に答える
0

段落記号の答えをさらに発展させるために、BクラスでAメンバーをオーバーライドすることにより、Aメンバーを好きなように簡単に初期化できます。

class B : public A
{
public:
    int a; // override a

    explicit B(int a1) : a(a1) // works now
    {
    }

    ...
};

しかし、私は必ずしもこれをお勧めしません;)

于 2009-08-20T04:41:26.480 に答える