1

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

4

3 回答 3

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

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

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

于 2019-03-19T10:39:13.790 回答
1

您还可以使用 C++11 功能:

class myClass
{
    private:
        //private:
        int timeN;
        anotherClass Object{ 500 };

    public:
        myClass(int _timeN) : timeN(_timeN) { }
        ~myClass() = default;
};

if Object 不依赖于任何构造函数参数。

于 2019-03-19T11:32:44.383 回答
1

有多种方法可以处理这种情况,具体取决于您在开发更多功能时的要求。

  1. 在 MyClass 指针中使用 anotherClass 的 指针 这样,您可以在标头中创建一个指针,并在构造函数中创建一个对象并传递所需的值。您必须记住删除构造函数中的指针。
#include "anotherClass.h"
class myClass
{
private:
    int timeN;
public:
    myClass(int timeN);
    anotherClass * m_pAnotherClass = nullptr; /* pointer to another class*/
    ~myClass();
};
#include "myClass.h"
myClass::myClass(int timeN) {
    this->timeN = timeN;
    //how to create anotherClass object where waitInt is e.g. 500?
    m_pAnotherClass = new anotherClass(500);
}

myClass::~myClass() {
    if(m_pAnotherClass == nullptr)
        delete m_pAnotherClass;  
 }

2 在 header 中创建对象并通过 setter 函数传递 waitInt。这样,您可以先为 anotherClass 创建一个对象,然后在 myClass 的构造函数中设置 int 值。当 myClass 对象被删除时, anotherClass 对象被删除。

#include "anotherClass.h"
class myClass
{
private:
    int timeN;
    anotherClass Object;        //Following timeN example, it would be declared like so 
public:
    myClass(int timeN);
    ~myClass();
};
#include "myClass.h"
myClass::myClass(int timeN) {
    this->timeN = timeN;
    //how to create anotherClass object where waitInt is e.g. 500?
    /* call setWaitInt mehtod and pass the value you want */
    Object.setWaitInt(500);
}

myClass::~myClass() {
}
{
private:
    int waitInt=0;
public:
    anotherClass();
    setWaitInt(int waitInt);

    ~anotherClass();
};
#include "anotherClass.h"

anotherClass::anotherClass()
{
}
anotherClass::setWaitInt(int waitInt)
{
    this->waitInt = waitInt;
}
anotherClass::~anotherClass(){}
于 2019-03-19T11:34:57.367 回答