0

我正在学习c++。我有一个这样的结构:

struct Info {

const Long rate;
A* ptr;

}

我有一个构造函数,它将所有参数作为其参数来初始化结构。但是,这个结构是另一个类的一部分,它将使用 boost 序列化进行序列化。为了序列化该类,我需要该结构的默认构造函数。但是,当我尝试编写默认构造函数时,例如

Info () {
}

我收到一个错误 C2758,表示应在构造函数中初始化成员费率。如何为这样的结构获取默认构造函数,我可以用它来序列化我的类。

4

4 回答 4

1

You can see the msdn documentation for C2758 for a description of the error.

In basic term's, a const variable must be initialised in all constructors. The compiler enforces that any built in type or pointer member that is const must be initialised when the object is constructed, as you won't get a chance to give it a meaningful value after construction ( if you could change it after it was created, how is it const ? ).

Also, as a general rule of thumb, it is always a good idea to initialise members that don't have a default constructor ( built in types, pointers, and objects without default constructors ) to something, in all your class constructors. Otherwise they will either be initialised to some random value ( primitives or pointers ), or you will get a compile error ( objects without default constructors ).

Info()
 : rate(0)
 , ptr(nullptr)
{
}

If you are assigning values to some of your parameters from constructor arguments, don't forget to assign a value to the other members as well.

Info( Long rate)
 : rate( rate )
 , ptr(nullptr)
{
}
于 2013-08-20T17:26:23.393 回答
1

该错误可能是由于您的Long类也没有默认构造函数。

有两种方法可以解决这个问题:

  • 将默认构造函数添加到Long, 或
  • 添加rateInfo的构造函数的初始化列表中。
于 2013-08-20T16:46:22.160 回答
1

您需要初始化常量值,因此:

Info () : rate(0) {
}
于 2013-08-20T16:44:23.837 回答
0

尝试这个 :

   struct Info {
      const Long rate;
      A* ptr;
      Info():rate(0){} // as Matthew guessed, call the correct Long constructor
                       // or define a default constructor for Long

   };
于 2013-08-20T16:47:44.477 回答