首页 > 解决方案 > 在一个类中声明另一个类的成员(它接受一个参数)?

问题描述

我正在为每个类使用一个 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。因此它希望不是重复的,因为链接帖子的所有答案都需要初始化列表,因此不回答我的问题。

标签: c++c++98

解决方案


#include "myClass.h"
myClass::myClass(int argsTimeN) : timeN(argTimeN), Object(500) {
}

这是在 C++ 中初始化类成员的正确方法。使用=运算符将​​复制您的对象(除非您重载了运算符)。

任何未以这种方式初始化的类属性,如果存在,将使用默认构造函数进行初始化


推荐阅读