C++ 如何初始化类数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2983819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:41:45  来源:igfitidea点击:

How initialize array of classes?

c++arrays

提问by Kra

I have this class constructor:

我有这个类构造函数:

Pairs (int Pos, char *Pre, char *Post, bool Attach = true);

How can I initialize array of Pairs classes? I tried:

如何初始化 Pairs 类的数组?我试过:

Pairs Holder[3] =
{
    {Input.find("as"), "Pre", "Post"},
    {Input.find("as"), "Pre", "Post"},
    {Input.find("as"), "Pre", "Post"}
};

Apparently it's not working, I also tried to use () brackets instead of {} but compiler keeps moaning all the time. Sorry if it is lame question, I googled quite hard but wasn't able to find answer :/

显然它不起作用,我也尝试使用 () 括号代替 {} 但编译器一直在抱怨。对不起,如果这是一个蹩脚的问题,我用谷歌搜索了很多,但无法找到答案:/

回答by

Call the constructor explicitly:

显式调用构造函数:

Pairs Holder[3] =
{
    Pairs(Input.find("as"), "Pre", "Post"),
    Pairs(Input.find("as"), "Pre", "Post"),
    Pairs(Input.find("as"), "Pre", "Post")
};

回答by Christian Neverdal

Call the constructor:

调用构造函数:

Pairs Holder[3] =
{
    Pairs(Input.find("as"), "Pre", "Post"),
    Pairs(Input.find("as"), "Pre", "Post"),
    Pairs(Input.find("as"), "Pre", "Post")
};

This is similar to saying

这类似于说

Holder[0] = Pairs(Input.find("as"), "Pre", "Post");
Holder[1] = Pairs(Input.find("as"), "Pre", "Post");
Holder[2] = Pairs(Input.find("as"), "Pre", "Post");

A full-fledged class can be found here.

一个完整的类可以在这里找到。