C++:数组的构造函数初始化器

76

我脑子有点抽...如何在C++中正确地初始化对象数组?

非数组示例:

struct Foo { Foo(int x) { /* ... */  } };

struct Bar { 
     Foo foo;

     Bar() : foo(4) {}
};

数组示例:

struct Foo { Foo(int x) { /* ... */  } };

struct Baz { 
     Foo foo[3];

     // ??? I know the following syntax is wrong, but what's correct?
     Baz() : foo[0](4), foo[1](5), foo[2](6) {}
};

编辑: 我欢迎各种奇思妙想的解决方案,但是它们在我的情况下没有用。我正在处理一个嵌入式处理器,在那儿 std::vector 和其他STL结构不可用,并且明显的解决方法是创建一个默认构造函数并拥有一个显式的 init() 方法,可以在构造后调用,这样我就不必使用初始化程序了。(这是那些被Java的 final 关键字和构造函数灵活性宠坏了的情况之一)。


5
好的,请提供需要翻译的内容。 - Jason S
9
为了简化教学,使用 struct 替代 class 不是更容易吗?我发现编译通过的代码更容易学习 ;-) - Steve Jessop
4
当我将你的代码复制到我的编译器时,我不得不添加你遗漏的部分。因此为了教学的简单性,你可以考虑不要让人们在未来帮助你变得困难。 - John Dibling
1
史蒂夫/约翰:两个都是真的。我错了。 - Jason S
1
@Jason:买一个,它是无价的。你也可以使用http://codepad.org/来编写类似这样的代码。 - Roger Pate
显示剩余2条评论
14个回答

0

来自扭曲思维的想法:

class mytwistedclass{
static std::vector<int> initVector;
mytwistedclass()
{
    //initialise with initVector[0] and then delete it :-)
}

};

现在将这个initVector设置成您想要的内容,然后再实例化一个对象。这样,您的对象就会用您的参数进行初始化。


0

这是我提供的参考解决方案:

struct Foo
{
    Foo(){}//used to make compiler happy!
    Foo(int x){/*...*/}
};

struct Bar
{
    Foo foo[3];

    Bar()
    {
        //initialize foo array here:
        for(int i=0;i<3;++i)
        {
            foo[i]=Foo(4+i);
        }
    }
};

-1
在 Visual Studio 2012 或以上的版本中,你可以这样做:
struct Foo { Foo(int x) { /* ... */  } };

struct Baz { 
     Foo foo[3];

     Baz() : foo() { }
};

-2
class C
{
   static const int myARRAY[10];  // only declaration !!!

   public:
   C(){}
   }

const int C::myARRAY[10]={0,1,2,3,4,5,6,7,8,9};  // here is definition

int main(void)
{
   C myObj;
   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接