本文介绍了C ++类初始化列表示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:

$ b。我将在新的Stroustrup书中阅读第17章,我对初始化一个初始化列表的类型感到困惑。
$ b

in .hpp:

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

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

在.cpp中:

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

}

或在.cpp中:

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

} / code>

并调用:

  A a {Carrot,10}; 

我在1998年学到了c ++,并且直到最近才开始编程。这个东西多久以前改变了?我知道我仍然可以这样做,但我真的想学习新的!

解决方案

首先我认为初始化列表是有用的当你处理常量成员或传递对象作为参数时,因为你避免调用默认构造函数,然后实际的赋值。



你应该在你的cpp中写下面的代码文件:无需重写初始化列表中的参数类型。

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

您的h档案应该是:

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

您应该创建一个新的A对象

  A new_object(string,12); 


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!

解决方案

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);

这篇关于C ++类初始化列表示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:36