如何在派生类构造函数中初始化基类成员变量?
问题描述:
为什么我不能这样做?
class A
{
public:
int a, b;
}
class B : public A
{
B() : A(), a(0), b(0)
{
}
}
>
I meant for the A member variables to be public.
答
您不能初始化 a
中的和
和
b
,因为它们不是 B
。它们是 A
的成员,因此只有 A
可以初始化它们。您可以将它们设为公开,然后在 B
中进行赋值,但这不是推荐的选项,因为它会破坏封装。而是在 A
中创建一个构造函数以允许 B
(或 A )初始化它们:
You can't initialize a
and b
in B
because they are not members of B
. They are members of A
, therefore only A
can initialize them. You can make them public, then do assignment in B
, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in A
to allow B
(or any subclass of A
) to initialize them:
class A
{
protected:
A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
// Change "protected" to "public" to allow others to instantiate A.
private:
int a, b; // Keep these variables private in A
};
class B : public A
{
public:
B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.
{
}
};