How can I initialize C++ object member variables in the constructor?(如何在构造函数中初始化 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++ 对象成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在构造函数中初始化 C++ 对象成员变量?
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01