C++ Class Initialization List example

北战南征 提交于 2019-12-23 02:18:09

问题


I am going through Chapter 17 in the new Stroustrup book and I am confused by initializing a class with an initialization list.

Example:

in .hpp:

class A
{
    public:
        A() : _plantName(std::string s), _growTimeMinutes(int 1);
        virtual ~A();

    private:
        std::string _plantName;
        int _growTimeMinutes;
};

in .cpp:

A::A() : _plantName(std::string s), _growTimeMinutes(int i)
{

}

or is it in .cpp:

A::A(std::string s, int i) : _plantName(std::string s), _growTimeMinutes(int i)
{

}

and calling that:

A a {"Carrot", 10};

I learned c++ back in 1998 and have only programmed in it off and on over the years until recently. How long ago did this stuff change? I know I could still do that the older way but I really want to learn new!


回答1:


First I think initialization lists are useful when when you are dealing with constant members or when passing objects as parameters since you avoid calling the default constructor then the actual assignement.

You should write the following code in your cpp file : no need to rewrite the parameters types in the initialization list.

A::A(std::string s, int i) : _plantName(s), _growTimeMinutes(i)
{
}

Your h file should be :

class A
{
    public:
         A(std::string, int);
    private:
        std::string _plantName;
        int _growTimeMinutes;
};

And you should create a new A object like that

A new_object("string", 12);



回答2:


It should be

A::A(std::string s, int i) : _plantName(s), _growTimeMinutes(i) {

}

for example

supposing the variables _plantName and _growTimeMinutes are declared within class A or one of its superclasses. s and i are the constructor parameters for class A, the initialization will then call the string-constructor for _plantName with argument s and the int-constructor for _growTimeMinutes with argument i, thus initializing both variables.

Initialization lists are especially needed if you want to initialize const references. The assignment within a constructor would not work.

Hope I could help



来源:https://stackoverflow.com/questions/16886983/c-class-initialization-list-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!