类的struct成员的默认初始化值 [英] default init value for struct member of a class

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

问题描述

下面的片段来自VC ++ 2008 Express Edition.说,我有一堂课,成员是一个结构.我正在尝试为此类的成员变量定义默认值.为什么这不起作用?

The fragment below is from a VC++ 2008 Express Edition. Say, I have a class with a member that is a struct. I am trying to define default values for the member variables of this class. Why this does not work?

struct Country{
    unsigned chart  id;
    unsigned int    initials;
    std::string name;
};

class world{
private:
    Country          _country;
    unsigned int    _population;
public:
    world(){};
    world():
             _country(): 
                 id('1'), initials(0), name("Spain") {};
             _population(543000) {}
    :
    :
    ~world(){};
};

推荐答案

有两种初始化国家/地区成员数据的方法.像这样...

There are two ways to initialize the country member data. Like this ...

struct Country{
    unsigned char   id;
    unsigned int    initials;
    std::string name;
};

class world{
private:
    Country          _country;
public:
     world()
     {
         _country.id = '1';
         _country.initials = 0;
         _country.name = "Spain";
     }
     ~world(){};
};

...或者像这样...

... or, like this ...

struct Country{
    unsigned char   _id;
    unsigned int    _initials;
    std::string _name;
    Country(
        unsigned char id,
        unsigned int initials,
        const std::string& name
        )
        : _id(id)
        , _initials(initials)
        , _name(name)
    {}
};

class world{
private:
    Country          _country;
public:
    world()
    : _country('1', 0, "Spain")
    {
    }
    ~world(){};
};

请注意,在第二个示例中,我发现初始化Country实例更加容易,因为我将构造函数定义为Country结构的成员.

Note that in the second example I find it easier to initialize the Country instance because I defined a constructor as a member of the Country struct.

或者,也许您想为Country类型提供默认的构造函数:

Or, perhaps you want to give the Country type a default constructor:

struct Country{
    unsigned char   _id;
    unsigned int    _initials;
    std::string _name;
    Country()
        : _id('1')
        , _initials(0)
        , _name("Spain")
    {}
};


class world{
private:
    Country          _country;
public:
    world()
    {
    }
    ~world(){};
};

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

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