C++结构和构造函数
关于 C++ 中的结构的一个快速问题,我尚未找到答案:
我读到结构和类之间的唯一区别是成员可见性。那么,编译器是否为该结构体提供了默认构造函数? (还有默认的复制构造函数、析构函数和赋值运算符?)您可以自己定义上述所有内容吗?
谢谢,伊斯特万
A quick question about structures in C++ that I haven't managed to find the answer for:
I've read that the only difference between structures and classes is the member-visibility. So, does the compiler give the structure a default constructor? (and a default copyconstructor, destructor, and assignment operator aswell?) And can you define all of the above yourself?
Thanks, István
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,确实如此,是的,你可以。
Yes, it does, and yes, you can.
是的,对你所有的问题。对于班级来说也是如此。
Yes to all your questions. The same holds true for classes.
没错。请注意,这包括继承的类:
在 S2 中,m2 和 m1 都具有公共可见性。并且可以在需要
S1*
的地方替换S2*
。Thats correct. Just to note that this includes inherited classes:
In S2, both m2 and m1 have public visibility. And an
S2*
can be substituted where anS1*
is expected.在 C++ 中,类和结构之间的唯一区别是类成员默认为私有,而结构成员默认为公共。因此结构可以有构造函数,并且语法与类相同。但前提是您的结构没有加入工会。
例如,
归功于此问题的答案。
In C++ the only difference between a
class
and astruct
is that class-members are private by default, whilestruct
-members default to public. So structures can have constructors, and the syntax is the same as for classes. But only if you do not have your structure in a union.e.g.
Credit goes to the answers in this question.