如何在派生类构造函数中初始化基类成员变量? [英] How can I initialize base class member variables in derived class constructor?
本文介绍了如何在派生类构造函数中初始化基类成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我不能这样做?
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.
{
}
};
这篇关于如何在派生类构造函数中初始化基类成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文