如何在构造函数中初始化 C++ 对象成员变量? [英] How can I initialize C++ object member variables in the constructor?

查看:40
本文介绍了如何在构造函数中初始化 C++ 对象成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,它有几个对象作为成员变量.我不希望在声明时调用这些成员的构造函数,所以我试图明确地挂在指向该对象的指针上.我不知道我在做什么.

I've got a class that has a couple of objects as member variables. I don't want the constructors for these members to be called when declared, so I'm trying to hang onto a pointer to the object explicitly. I have no idea what I'm doing.

我想也许我可以执行以下操作,在初始化对象成员变量时立即调用构造函数:

I thought maybe I could do the following, where the constructor is called immediately when initializing the object member variable:

class MyClass {
    public:
        MyClass(int n);
    private:
        AnotherClass another(100); // Construct AnotherClass right away!
};

但我希望 MyClass 构造函数调用 AnotherClass 构造函数.这是我的代码的样子:

But I want the MyClass constructor to call the AnotherClass constructor. Here's what my code looks like:

#include "ThingOne.h"
#include "ThingTwo.h"

class BigMommaClass {

        public:
                BigMommaClass(int numba1, int numba2);

        private:
                ThingOne* ThingOne;
                ThingTwo* ThingTwo;
};

文件 BigMommaClass.cpp

#include "BigMommaClass.h"

BigMommaClass::BigMommaClass(int numba1, int numba2) {
        this->ThingOne = ThingOne(100);
        this->ThingTwo = ThingTwo(numba1, numba2);
}

这是我尝试编译时遇到的错误:

Here's the error I'm getting when I try to compile:

g++ -Wall -c -Iclasses -o objects/BigMommaClass.o classes/BigMommaClass.cpp
In file included from classes/BigMommaClass.cpp:1:0:
classes/BigMommaClass.h:12:8: error: declaration of âThingTwo* BigMommaClass::ThingTwoâ
classes/ThingTwo.h:1:11: error: changes meaning of âThingTwoâ from âclass ThingTwoâ
classes/BigMommaClass.cpp: In constructor âBigMommaClass::BigMommaClass(int, int)â:
classes/BigMommaClass.cpp:4:30: error: cannot convert âThingOneâ to âThingOne*â in assignment
classes/BigMommaClass.cpp:5:37: error: â((BigMommaClass*)this)->BigMommaClass::ThingTwoâ cannot be used as a function
make: *** [BigMommaClass.o] Error 1

我是否使用了正确的方法,但使用了错误的语法?或者我应该从不同的方向来解决这个问题?

Am I using the right approach, but the wrong syntax? Or should I be coming at this from a different direction?

推荐答案

可以在成员初始化列表中指定如何初始化成员:

You can specify how to initialize members in the member initializer list:

BigMommaClass {
    BigMommaClass(int, int);

private:
    ThingOne thingOne;
    ThingTwo thingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
    : thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}

这篇关于如何在构造函数中初始化 C++ 对象成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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