如何初始化没有默认成员的对象的成员数组? [英] How can I initialise a member array of objects that don't have a default constuctor?

查看:139
本文介绍了如何初始化没有默认成员的对象的成员数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以告诉我应该如何初始化对象的成员数组,在对象没有默认构造函数(即需要参数)的情况下。

I was wondering if anyone could tell me how I'm supposed to initialise a member array of objects, in the occasion that the object does not have a default constructor (i.e. requires parameters).

例如:

class Foo
{
public:
   Foo() : 
      memberArray{bar(1), bar(3), bar(2)}   // **The compiler doesnt like this** 
   {}
private:
   Bar memberArray[3];
};


struct Bar
{
   Bar(std::int32_t param1) {  }
}

我使用GCC 4.6.1和编译c ++ 11。任何人都可以指出我在哪里错了? (BTW,请不要建议动态分配的内存,因为我没有它。)

I'm using GCC 4.6.1, and compiling for c++11. Can anyone point out where I'm going wrong? (BTW. please don't suggest dynamically allocated memory, as I don't have it..)

推荐答案

有几个问题:不一致的情况下,声明前使用,缺少分号,缺少包含。这是非常接近的:

You've got several problems: inconsistent case, use before declaration, missing semicolons, missing includes. This is a lot closer:

struct Bar
{
   Bar(int param1) {  }
};

class Foo
{
public:
   Foo() : 
      memberArray{Bar(1), Bar(3), Bar(2)}
   {}
private:
   Bar memberArray[3];
};

这篇关于如何初始化没有默认成员的对象的成员数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆