繁体   English   中英

初始化在C ++中的private类中声明的struct对象

[英]initializing struct object declared in class private in c++

我在类内部声明了我的struct对象,并使用构造函数对其进行了初始化,但是我的样式检查器说我的struct类型的成员函数未初始化。 在这方面,谁能帮助我,我将非常感谢您。

下面是我的代码,请提出一些解决此问题的方法

class Datastructure{

  //forward decleration
  struct Ship;

public:

  //Constructor DS class
  Datastructure();

 //Destructor DS class
  ~Datastructure();



private:

   struct Ship{
     std::string s_class;
     std::string name;
     unsigned int length;
     Ship();
     Ship(const std::string& shipClass, const std::string& shipName,
          unsigned int len);
   };

  Ship minShip;
  Ship maxShip;
  std::vector<Ship> shipVector;
};

#endif

它给我以下警告

  CIMP, line 17: Uninitialized member variables in class 'Datastructure'.
  FSCH, line 17: No access specifiers at the beginning of class
                 'Datastructure'.
  IVAP, line 62: Field 'minShip' in class 'Datastructure' is not initialized.
  IVAP, line 63: Field 'maxShip' in class 'Datastructure' is not initialized.
  IVAP, line 64: Field 'shipVector' in class 'Datastructure' is not
                 initialized.

成员变量 minShipmaxShip需要在 maxShip构造 函数初始化 例如,

 
 
 
  
  DataStructure() : minShip(), maxShip(), shipVector() {}
 
  

尽管不是错误的做法,但最好提供Ship构造函数的实现,以便将length初始化为已知(而不是随机)值。

Ship() : length() {}

上面的语法与

Ship() : length( 0 ) {}

因为

int i = int();

i初始化为0

根据C ++标准,minShip,maxShip和shipVector已使用其默认构造函数进行了初始化。

但是,您表示您正在使用样式检查器。 您的样式指南可能需要显式调用默认构造函数。 这样做的原因之一是确保您调用正确的构造函数,而不依赖于自动行为-这不是标准所要求的,甚至不是典型的C ++程序员所做的,但这不是您的样式,而是样式检查器对其进行了标记,您可能只需要遵守。

在不同的组织中存在着各种各样的样式规则,这些规则对于编译器不是必需的,但是也许可以使开发人员更容易理解彼此的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM