简体   繁体   English

结构和类成员结构 C++

[英]Struct and Classes member structure c++

When creating struct or classes, usually attributes don't have a specific value at all, and when they call the constructor, they assign the values that they want.在创建结构体或类时,通常属性根本没有特定的值,当它们调用构造函数时,它们会分配所需的值。

struct Point{
    int x;
    int y;
}

Point myPoint = {0,0};

However when is appropriate the following case?但是,什么时候适合以下情况?

struct Point{
    int x = 0;
    int y = 0;
}

I'm in some sort of way trying to specify the default values of each attribute, then change it when necessary我以某种方式尝试指定每个属性的默认值,然后在必要时更改它

Point center; //This is (0,0) by default

Point myPoint;
myPoint.x = 7;
myPoint.y = 14;

Also, are these approaches valid when working with classes?此外,这些方法在使用类时有效吗?

However when is appropriate the following case?但是,什么时候适合以下情况? [example with default member initialisers] [具有默认成员初始值设定项的示例]

Depends on what standard version you use, and what you need from the class:取决于您使用的标准版本,以及您需要从课程中获得的内容:

  • It is not appropriate prior to C++11 because that is when default member initialisers were introduced to the language.它在 C++11 之前是不合适的,因为那是在语言中引入默认成员初始值设定项的时候。
  • It is not appropriate prior to C++14 if you need the class to be an aggregate, because default member initialisers would disqualify the class from being an aggregate prior to that version.如果您需要将类作为聚合,则在 C++14 之前是不合适的,因为默认成员初始值设定项会取消该类在该版本之前成为聚合的资格。

Otherwise it is appropriate to provide default member initialisers assuming reasonable defaults exist.否则,假设存在合理的默认值,则提供默认成员初始值设定项是合适的。

Also, are these approaches valid when working with classes?此外,这些方法在使用类时有效吗?

Yes;是的; both are valid.两者都是有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM