如果我不明确地初始化,C++ 类成员如何初始化?

假设我有一个包含私有成员的类 ptrnamepnamernamecrnameage.如果我不自己初始化它们会怎样?这是一个例子:

类示例 {私人的:诠释*ptr;字符串名称;字符串 *pname;字符串 &rname;常量字符串 &crname;年龄;上市:例子() {}};

然后我做:

int main() {示例例如;}

ex 中的成员是如何初始化的?指针会发生什么?stringint 是否使用默认构造函数 string()int() 进行 0 初始化?参考成员呢?还有 const 引用呢?

我想学习它,以便编写更好(无错误)的程序.任何反馈都会有所帮助!

解决方案

类中成员的初始化与函数中局部变量的初始化相同,而不是显式初始化.

对于对象,调用它们的默认构造函数.例如,对于 std::string,默认构造函数将其设置为空字符串.如果对象的类没有默认构造函数,如果不显式初始化就会出现编译错误.

对于原始类型(指针、整数等),它们未初始化――它们包含之前碰巧出现在该内存位置的任意垃圾.p>

对于references(例如std::string&),不初始化它们是非法,你的编译器会抱怨并拒绝编译这样的代码.必须始终初始化引用.

因此,在您的具体情况下,如果它们没有显式初始化:

 int *ptr;//包含垃圾字符串名称;//空字符串字符串 *pname;//包含垃圾字符串 &rname;//编译错误常量字符串 &crname;//编译错误年龄;//包含垃圾

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() {}
};

And then I do:

int main() {
    Example ex;
}

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?

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.

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.

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

相关文章