我正在为每个类使用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();
};
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() {}
anotherClass.h:
class anotherClass;
{
private:
int waitInt;
public:
anotherClass(int waitInt);
~anotherClass();
};
anotherClass.cpp:
#include "anotherClass.h"
anotherClass::anotherClass(int waitInt)
{
this->waitInt = waitInt;
}
anotherClass::~anotherClass(){}
编辑:我不能使用初始化列表,我正在使用C ++ 98。因此,希望它不会重复,因为链接文章的所有答案都需要初始化列表,因此不会回答我的问题。
答案 0 :(得分:2)
#include "myClass.h"
myClass::myClass(int argsTimeN) : timeN(argTimeN), Object(500) {
}
这是在C ++中初始化类成员的正确方法。使用=
运算符将复制您的对象(除非您使运算符重载)。
任何不以这种方式初始化的类属性,都将使用默认构造函数进行初始化
答案 1 :(得分:1)
您还可以使用C ++ 11功能:
class myClass
{
private:
//private:
int timeN;
anotherClass Object{ 500 };
public:
myClass(int _timeN) : timeN(_timeN) { }
~myClass() = default;
};
如果Object不依赖于任何构造函数参数。
答案 2 :(得分:1)
有多种方法可以处理这种情况,具体取决于您在开发更多功能时的要求。
#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在标头中创建对象,然后通过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(){}