关于 c++ 的推导问题
为什么我无法访问基类 A 的 B 类初始化列表中的成员?
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;
}
};
Why I can't access base class A's a member in class B initialization list?
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;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
A 的构造函数在 B 的构造函数之前运行,并且隐式或显式地,前者构造了 A 的所有实例,包括
a
成员。 因此 B 不能在a
上使用构造函数,因为该字段已经构造完毕。 您尝试使用的符号准确地表明在a
上使用构造函数,而此时这是不可能的。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 ona
, because that field is already constructed. The notation you're trying to use indicates exactly to use a constructor ona
, and at that point it's just impossible.要以 Alex 的答案为基础,您可以通过控制其构造来初始化基类的 "a" 成员,如下所示:
请注意,我正在构造基类(大写 "A" ),而不是尝试直接初始化其继承的成员(小写“a”,取自您的示例)。
To build on Alex' answer, you can initialize the base class' "a" member by controlling its construction, like so:
Note that I'm constructing the base class (capital "A") above, rather than attempting to directly initialize its inherited member (lowercase "a", drawing from your example).
为了进一步构建 pilcrow 的答案,您可以通过在 B 类中覆盖它来轻松地初始化 A 成员,就像您想要的那样:
不过,我不一定推荐这样做;)
To build even further on pilcrow's answer, you could easily initialize the A member like you want by overriding it in your B class:
Though, I wouldn't necessarily recommend this ;)