调用默认构造函数的正确方法是什么? [英] What is the proper way to call default constructors?

查看:214
本文介绍了调用默认构造函数的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在构造函数方面遇到困难,并且与其他问题和指南的不同尝试总是有某种形式的segfault在运行时等待我(编译我花在编程中的80%的时间)。



以下示例显示了我想要完成的基本概念:

  struct Coord3 {
float x,y,z;
Coord3(){x = 0; y = 0; z = 0;}; ///这是正确的吗?
};

struct Stat {
int Str,Dex,Int;
Stat(){Str = 0; Dex = 0; Int = 0;};
};

struct Item {
Stat myStats;
Item(){...};
};

class SimpleChar {
public:///保持现在简单
Coord3 pos;
Stat myStats;
int level;
float health;
项目清单[20];

SimpleChar(){
level = 0;
health = 100;
} ///在这个类的构造函数中,'pos','inventory'和'myStats'会发生什么?
};

int main(){
SimpleChar myChar;
if(myChar.inventory [0] .get()!= NULL){...} ///这会导致最新的SEGFAULT,如下所述。为什么不工作?对于这个例子,我有一些更简单的结构(类似于<$ c())

Coord3 和 Stat )。这些结构在我的引擎的基础级别,并相应地用于制作更高级别的结构,然后这些结构用于使最高级别的结构(例如 Item 是项目相关信息, SimpleChar 具有通用RPG字符统计信息,如库存和统计信息)。我得到的错误是非常不同的,根据情况,很难跟踪他们所有的情况,但最有趣的是一个SEGFAULT:



if(itemSet.inventory [a] .get()!= NULL); ///注意:这本来是一个shared_ptr,在一个称为ItemSet的结构中,它保存了所有项目信息。



我要求的是:


  1. 默认构造函数何时被调用?


  2. 在类和 main()中声明这些成员的正确方法

  3. 创建构造函数的正确方法是什么?



编辑2:因为SEGFAULT是一个非常有用的代码,不是从构造函数格式创建然后我问,如果一个实例变量的大小太大可能得到一个SEGFAULT?我主要问这个,因为最近我把一个类成员改为一个指针而不是一个对象,它工作正常。

解决方案

你清除了类:

  class foo {
public:
foo这是默认构造函数
};

但如果你写:

  class foo {}; 

编译器将为您提供一个默认构造函数。当你写:

  class SimpleChar {
Coord3 pos; //将调用Coord3的默认构造函数,
//如果您需要在SimpleChar构造函数中执行此操作;
Stat myStats; // same
int level;
float health;
项目清单[20]; //一个数组将被创建,可以容纳20个项目,
//构造函数(默认)将被调用20次


};

如果要使用默认构造函数初始化对象,请在main()内部:

  className instanceName; 

就足够了。


当您写:

  SimpleChar myChar; 

以下构造函数被调用:

  SimpleChar(){
level = 0;
health = 100;
};

另外一点; 一个类或结构体定义之后的类型或结构体定义,在struct item {}中不存在


struct的默认访问说明符是public, ,这意味着您无法使用默认构造函数在main中创建对象。

编辑:
如果实例变量尺寸太大,您可能会收到 std :: bad_alloc 如果它在运行时动态分配,但通常不是segfault。它发生在你访问你没有自己的区域。


Lately I have been having difficulties with constructors, and the different attempts from other questions and guides always have some form of segfault waiting for me at runtime (making compiling 80% of my time spent programming).

The following example shows the basic idea on what I am trying to accomplish:

struct Coord3{
    float x, y, z;
    Coord3() {x=0;y=0;z=0;};///Is this Correct?
};

struct Stat{
    int Str,Dex,Int;
    Stat(){Str=0;Dex=0;Int=0;};
};

struct Item{
    Stat myStats;
    Item(){...};
};

class SimpleChar{
    public: ///to keep things simple for now
    Coord3 pos;
    Stat myStats;
    int level;
    float health;
    Item inventory[20];

    SimpleChar(){
    level=0;
    health=100;
    }///What happens with 'pos', 'inventory' and 'myStats' in this class's constructor?
};

int main(){
    SimpleChar myChar;
    if(myChar.inventory[0].get()!=NULL){...}///this caused the most recent SEGFAULT as mentioned below. Why wouldn't this work?
}

With this example I have a bunch of simpler structs (similar to Coord3 and Stat). These structs are at the base level of my "engine", and are used accordingly to make higher level structs, then those are used to make the highest level structs (such as Item being item related information and SimpleChar having generic RPG character statistics, like an inventory and stats). The errors I get are so different according to the situation that it was difficult to keep track them all, but the most interesting one was a SEGFAULT on:

if(itemSet.inventory[a].get()!=NULL); ///Note: this is originally a shared_ptr AND was in a struct known as 'ItemSet', which held all item information

So basically what I ask is:

  1. When are the default constructors invoked?
  2. When the constructors are used, do they also invoke their member's constructors?
  3. What would be the correct way to declare these members both in the classes and main()?
  4. What is the correct way to create the constructor?

EDIT: The code has been spruced up for anyone that is way too obsessed with if the code is "valid by syntax" instead of actually answering the question.

EDIT 2: Since the SEGFAULTs are not created from constructor format then I ask if it is possible to get a SEGFAULT if an instance variable is too large in size? I mainly ask this because recently I have changed a class member to a pointer instead of an object and it worked fine.

解决方案

when you declear a class like:

class foo{
    public:
    foo(){} // this is default constructor
};

But if you write:

class foo{};

The compiler will supply a default constructor for you. When you write:

class SimpleChar{
    Coord3 pos;   // default constructor of Coord3 will be called, 
                  //if you need somrthing else do that in SimpleChar constructor;
    Stat myStats; // same
    int level;
    float health;
    Item inventory[20];    // an array will be created that can hold 20 item,
                           // constructor (default) will be called 20 times


};

Inside main() if you want to initialise an object with default constructor:

className instanceName; 

is enough.

When You write:

SimpleChar myChar;

The following constructor is called:

SimpleChar(){
    level=0;
    health=100;
    };

An additional point ; is mandetory after a class or struct definetion, which is absent in struct item{}

And default access specifier of struct is public but in class it is private, Which means you can not create object in main with default constructor.

Edit: "if an instance variable is too large in size" you may get a std::bad_alloc if it is being allocated dynamically in runtime but generally not a segfault. it happens when you access area you do not own.

这篇关于调用默认构造函数的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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