如果我不明确地做,C ++类成员如何初始化? [英] How do C++ class members get initialized if I don't do it explicitly?

查看:120
本文介绍了如果我不明确地做,C ++类成员如何初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类有私人内存 ptr name pname rname crname age 。如果我不自己初始化它会发生什么?这里是一个例子:

Suppose I have a class with private memebers ptr, name, pname, rname, crname and age. What happens if I don't initialize them myself? Here is an example:

class Example {
    private:
        int *ptr;
        string name;
        string *pname;
        string &rname;
        const string &crname;
        int age;

    public:
        Example() {}
};

然后我:

int main() {
    Example ex;
}

如何在ex中初始化成员?指针会发生什么? $ string int get 0-intialized with default constructors string $ c>和 int()?参考成员怎么办?还有什么关于const引用?

How are the members initialized in ex? What happens with pointers? Do string and int get 0-intialized with default constructors string() and int()? What about the reference member? Also what about const references?

我还应该知道什么?

这些情况?也许在一些书?我可以在大学的图书馆访问很多C ++书。

Does anyone know a tutorial that covers these cases? Maybe in some books? I have access in university's library to a lot of C++ books.

我想学习它,所以我可以写更好的(无bug的)程序。任何反馈将有所帮助!

I'd like to learn it so I can write better (bug free) programs. Any feedback would help!

推荐答案

代替初始化显式初始化,类中的成员初始化与函数中局部变量的初始化

In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions.

对于对象,将调用其默认构造函数。例如,对于 std :: string ,默认构造函数将其设置为空字符串。如果对象的类没有默认的构造函数,如果你没有显式地初始化它将是一个编译错误。

For objects, their default constructor is called. For example, for std::string, the default constructor sets it to an empty string. If the object's class does not have a default constructor, it will be a compile error if you do not explicitly initialize it.

对于原始类型 (指针,整数等),它们不是初始化的 - 它们包含以前在该存储器位置发生的任何任意垃圾。

For primitive types (pointers, ints, etc), they are not initialized -- they contain whatever arbitrary junk happened to be at that memory location previously.

对于引用(例如 std :: string& ),它是非法的不初始化它们,抱怨和拒绝编译这样的代码。

For references (e.g. std::string&), it is illegal not to initialize them, and your compiler will complain and refuse to compile such code. References must always be initialized.

所以,在你的具体情况下,如果他们没有显式初始化:

So, in your specific case, if they are not explicitly initialized:

    int *ptr;  // Contains junk
    string name;  // Empty string
    string *pname;  // Contains junk
    string &rname;  // Compile error
    const string &crname;  // Compile error
    int age;  // Contains junk

这篇关于如果我不明确地做,C ++类成员如何初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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