显式初始化没有默认构造函数的成员 [英] Explicitly initialize member which does not have a default constructor
问题描述
我试图实例化一个没有默认构造函数的对象,因此可以从类中的任何方法引用它。我在我的头文件中声明它,但编译器说,创建它的类的构造函数必须显式初始化成员,我不能弄清楚如何做。
I´m trying to instantiate an object which has no default constructor so it can be referenced from any methods inside the class. I declared it in my header file, but the compiler says that the constructor for the class creating it must explicitly initialize the member, and I can´t figure out how to do that.
非常感谢您的回答,提前谢谢!
Really appreciate your answers, thank you in advance!
MyClass.h
MyClass.h
include "MyOtherClass.h"
class myClass {
private:
MyOtherClass myObject;
public:
MyClass();
~MyClass();
void myMethod();
}
MyClass.cpp
MyClass.cpp
include "MyClass.h"
MyClass::MyClass() {
MyOtherClass myObject (60);
myObject.doSomething();
}
MyClass::myMethod() {
myObject.doSomething();
}
MyOtherClass.h
MyOtherClass.h
class MyOtherClass {
private:
int aNumber;
public:
MyOtherClass (int someNumber);
~MyOtherClass();
void doSomething();
}
MyOtherClass.cpp
MyOtherClass.cpp
include "MyOtherClass.h"
MyOtherClass::MyOtherClass (int someNumber) {
aNumber = someNumber;
}
void MyOtherClass::doSomething () {
std::cout << aNumber;
}
推荐答案
当你在c ++中创建一个对象,默认情况下,它运行所有的对象的默认构造函数。你可以通过这个来告诉要使用的构造函数的语言:
You are almost there. When you create a object in c++, by default it runs the default constructor on all of it's objects. You can tell the language which constructor to use by this:
MyClass::MyClass() : myObject(60){
myObject.doSomething();
}
这样就不会试图找到默认构造函数并呼叫您想要哪一个。
That way it doesn't try to find the default constructor and calls which one you want.
这篇关于显式初始化没有默认构造函数的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!