如何将基类子对象的成员初始化为0?
class A
{
public: int a,b,c;
};
class B: public A
{
public: int d;
B():d(0){} // Some hackery needed here
};
int main()
{
B obj;
std::cout<< obj.a << std::endl; // garbage
std::cout<< obj.b << std::endl; // garbage
std::cout<< obj.c << std::endl; // garbage
std::cout<< obj.d << std::endl; // 0
}
子对象数据成员a、b、c如何初始化为0?我无权修改 A 类。
class A
{
public: int a,b,c;
};
class B: public A
{
public: int d;
B():d(0){} // Some hackery needed here
};
int main()
{
B obj;
std::cout<< obj.a << std::endl; // garbage
std::cout<< obj.b << std::endl; // garbage
std::cout<< obj.c << std::endl; // garbage
std::cout<< obj.d << std::endl; // 0
}
How could the subobject data members a,b and c be initialized to 0? I am not permitted to modify class A.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Try
A() 值初始化 A,并且由于 A 是 POD,因此成员将被默认(零)初始化
Try
A() value initializes A and since A is a POD the members will be default(zero) initialized
我测试了这个,因为我认为它可能有效(即使没有 Prasoon 的答案)
可能有效,因为你然后“初始化”A。
顺便说一句,它没有。输出:
1,32,123595988
但这可以工作:
其次是:
我正在使用 g++ 4.3.2 进行测试。现在这起作用了:
I tested this as I thought it might work (even without Prasoon's answer)
might work, because you are then "initialising" A.
It didn't, by the way. Output:
1,32,123595988
This would work though:
followed by:
I am testing using g++ 4.3.2. Now THIS worked:
也许我错过了一些东西,但是这个怎么样?
Perhaps I'm missing something, but how about this?
正确的方法当然是让 A 的构造函数初始化它的成员。否则,由于成员不是私有的,您可以从 B 构造函数内部为它们分配值。
等等,确实有效。
The proper way is of course to have A's constructor initialize it's members. Otherwise, as the members are not private, you can assign them values from inside the B constructor.
etc, actually works.
声明派生类构造函数,如下所示
declare the derived class constructor as shown below