c++ - 在一个类中声明另一个类的成员(它接受一个参数)?
问题描述
我正在为每个类使用一个 cpp 和 .h 文件,我很困惑如何使用另一个具有带参数的构造函数的类的成员。
MyClass.h:
#include "anotherClass.h"
class myClass
{
private:
int timeN;
anotherClass Object; //Following timeN example, it would be declared like so
public:
myClass(int timeN);
~myClass();
};
我的类.cpp:
#include "myClass.h"
myClass::myClass(int timeN) {
this->timeN = timeN;
//how to create anotherClass object where waitInt is e.g. 500?
}
myClass::~myClass() {}
另一个类.h:
class anotherClass;
{
private:
int waitInt;
public:
anotherClass(int waitInt);
~anotherClass();
};
另一个类.cpp:
#include "anotherClass.h"
anotherClass::anotherClass(int waitInt)
{
this->waitInt = waitInt;
}
anotherClass::~anotherClass(){}
编辑:我不能使用初始化列表,我正在使用 C++98。因此它希望不是重复的,因为链接帖子的所有答案都需要初始化列表,因此不回答我的问题。
解决方案
#include "myClass.h"
myClass::myClass(int argsTimeN) : timeN(argTimeN), Object(500) {
}
这是在 C++ 中初始化类成员的正确方法。使用=
运算符将复制您的对象(除非您重载了运算符)。
任何未以这种方式初始化的类属性,如果存在,将使用默认构造函数进行初始化
推荐阅读
- splunk - 从 ossec 升级到 wazuh - “本地/独立”模式?
- spring-data-jpa - 以通用方式扩展 JpaRepository,同时可以访问它的方法(即没有新的基础项目存储库或单存储库扩展接口)
- sql-server - 窗口函数没有给出运行总数
- bad-gateway - 我想通过拦截器重现 502 bad gateway 错误。任何步骤如何重现它?
- amazon-web-services - sagemaker 'metric_definitions' 没有给出任何结果
- assembly - 使用 Dosbox 比较汇编语言 [MASM] 中的浮点数
- ruby-on-rails - 将数据从一个(可怕的)数据库增量复制到 Rails 中的另一个(更好的)数据库
- pytorch - 使用 PyTorch 模型执行推理时子进程挂起
- python - 如何删除 Wordcloud 中的标点符号?
- spring - Spring 声明式缓存测试仅在测试直接调用 @Cacheable 方法时才有效