使用输入参数初始化结构

时间:2011-02-17 09:37:14

标签: c++ boost struct initialization c++11

我是c ++的新手,我在使用成员函数 occ_stat_t 初始化容器 CNetwork::CNetwork 时遇到问题。

我猜行中出现了问题: occ_stat[0]( num_elements_ ) , occ_stat[1]( num_elements_ ) 但我真的不知道如何正确地写它。

我想了解如何初始化我的结构,在每个 occ_stat 中, occupied_counter 将包含 {{1 } 元素和 n 将分配值mean_life_time

我将不胜感激。

问候

0

2 个答案:

答案 0 :(得分:1)

我不知道是否可以在初始化列表中访问数组下标。除非在C ++ 0x上 - 你是 - 但在VS 2010中没有,因为它没有在那里实现。

所以你必须:

CNetwork::CNetwork ( uint32_t num_elements_ ) 
{
    occ_stat[0].occupied_counter =  boost::extents[num_elements_];
    occ_stat[1].occupied_counter =  boost::extents[num_elements_];

    //or 

    occ_stat[0] = occ_stat_t(num_elements_);
    occ_stat[1] = occ_stat_t(num_elements_);

    // do something
}

编辑:

好的,所以你还要添加一个默认构造函数,因为我们在初始化列表中初始化它,所以:

struct occ_stat_t {

    occ_stat_t () : occupied_countr(/*default_to_whatever_boost_extents is*/){};

    /* Don't need this one we default construct now
    occ_stat_t (uint32_t n ):
            occupied_counter( boost::extents[n] ) {}
    */

    uint32_1d_t occupied_counter;
    double      mean_life_time;
};

答案 1 :(得分:0)

原始数组中的元素仅使用其默认构造函数 构造。所以你不能初始化这样的数据成员。

但是,为什么需要数组[2]数据成员occ_stat? 拥有2个具有更具体名称的成员会不会更好?

class CNetwork {
public:
    CNetwork ( uint32_t num_elements_ );

private:
    occ_stat_t  occ_stat_for_somthing;
    occ_stat_t  occ_stat_for_another;

};

CNetwork::CNetwork ( uint32_t num_elements_ ) 
:
  occ_stat_for_something( num_elements_ ) , 
  occ_stat_for_another( num_elements_ )
{
}