初始化类的私有成员变量 [英] Initializing private member variables of a class

查看:186
本文介绍了初始化类的私有成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提前致歉,因为我的一些措辞可能不是100%正确。

I apologize in advance because some of my verbiage may not be 100% correct.

我将拥有这样的课程:

class ClassName {
private:
    AnotherClass class2;
public:
  ClassName();
  ~ClassName();
...

在此类的构造函数中,我将

In the constructor of this class, among other things, I put the line

ClassName::ClassName() {
    AnotherClass class2; 
}

我以为您应该使用C ++初始化对象(通过GDB)注意到正在创建两个AnotherClass对象。一次在构造函数定义中,然后再次在我的初始化行中。这背后的原因是什么?如果我想使用更复杂的构造函数,如 AnotherClass(int a,int b),该方法会创建一个临时对象,然后在不久后创建正确的对象吗?

Which is how I thought you were supposed to initialize objects in C++, however I was noticing (through GDB) that two AnotherClass objects were being created. Once on the Constructor definition then again on my initialization line. What is the reasoning behind this? What if I wanted to use a more complicated constructor like AnotherClass(int a, int b), would it create a temporary object then create the correct one shortly after?

推荐答案

AnotherClass class2; 在构造函数主体内创建另一个本地对象,在身体末端被摧毁。

AnotherClass class2; creates another local object inside the constructor body, that gets destroyed at the end of the body. That is not how class members are initialized.

在构造函数签名和主体之间的成员初始化器列表中的构造函数主体之前,初始化类成员。 ,以开头,就像这样:

Class members are initialized before the constructor body in the member initializer list between the constructor signature and body, starting with a :, like so:

ClassName::ClassName() :
    class2(argumentsToPassToClass2Constructor),
    anotherMember(42) // just for example
{
    /* constructor body, usually empty */
}

如果您不想将任何参数传递给 class2 构造函数,您不必将其放在初始化列表中。然后,将调用其默认构造函数。

If you don't want to pass any arguments to the class2 constructor you don't have to put it in the initializer list. Then its default constructor will be called.

如果只想在所有类成员上调用默认构造函数,则可以(并且应该)完全省略该构造函数。隐式生成的默认构造函数将执行您想要的操作。

If you simply want to call the default constructor on all of your class members, you can (and should) omit the constructor altogether. The implicitly generated default constructor will do just what you wanted.

这篇关于初始化类的私有成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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