最佳答案
我有一个类,它有几个对象作为成员变量。我不希望这些成员的构造函数在声明时被调用,所以我试图显式地挂起一个指向对象的指针。我不知道我在做什么。
我想也许我可以执行以下操作,在初始化 object 成员变量时立即调用构造函数:
class MyClass {
public:
MyClass(int n);
private:
AnotherClass another(100); // Construct AnotherClass right away!
};
但是我想让 MyClass
构造函数调用 AnotherClass
构造函数:
#include "ThingOne.h"
#include "ThingTwo.h"
class BigMommaClass {
public:
BigMommaClass(int numba1, int numba2);
private:
ThingOne* ThingOne;
ThingTwo* ThingTwo;
};
#include "BigMommaClass.h"
BigMommaClass::BigMommaClass(int numba1, int numba2) {
this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);
}
下面是我尝试编译时遇到的错误:
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
我使用的方法是否正确,但语法是否错误?还是我应该从另一个角度来看这个问题?