创建和初始化struct数组

时间:2015-11-14 09:24:11

标签: arrays struct

我希望结构数组的实例具有各自的名称,但是从我在初始化结构实例时看到的示例中,我不知道该怎么做。但是......我想做这样的事情:

{{1}}

但是这没有用,所以我想知道我该如何去做呢

1 个答案:

答案 0 :(得分:0)

首先,类,枚举和结构以';'终止。在结束括号(或范围)之后。 即。

struct St {
    ....
};//<--- end of scope terminator

接下来,你到底想要做什么呢?我猜测你是在试图定义它的使用情况,但你完全错了。你需要在struct中有一个成员来设置一个值,这可以是struct本身的一个实例。像这样......

struct St {
    St element;
};

然后你可以为structs成员设置一个值,但是在这个特定的例子中,你可能想要更多的数据成员来使用这个结构......

struct St {
     char value;
     St element;
     St(char value, St element) // struct constructor
         : this->value(value), this->element(element){} // init list
};

现在你可以在代码的其余部分中使用结构,只需通过它的标识符来调用它,在这种情况下它将是&#39; St&#39;。

虽然,你想要实现的目标(我可能是错的)更适合于枚举值,这基本上是一种定义你自己的原始,可切换,变量类型的方法。枚举有用的例子就是......

const int MON = 0, TUE = 1, ....// rather than using "const int's"
// define them as enumerations
enum Day {MON,TUE,WED,THU,FRI,SAT,SUN};

/*each enum is assigned an integer ordinal that corresponds to its location
  as it is declared, so MON == 0, TUE == 1, and so on. You can alternatively 
  assign your own value to it in an instance where the default ordinal would 
  not be useful, for instance if you wanted them as characters...*/

enum Foo {Bar = 'B', Qat = 'Q', ...};

// or

enum Ratings {PG13 = 13, R = 18, ...};

您可能会受益于以下资源:

http://www.tutorialspoint.com/cplusplus/cpp_references.htm

http://en.cppreference.com/w/