Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

c++ - 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!

The snippet:

MyClass.h

include "MyOtherClass.h"

class myClass {

    private:
        MyOtherClass myObject;

    public:
        MyClass();
        ~MyClass();
        void myMethod();

}

MyClass.cpp

include "MyClass.h"

MyClass::MyClass() {

   MyOtherClass myObject (60);
   myObject.doSomething();

}

MyClass::myMethod() {

    myObject.doSomething();

}

MyOtherClass.h

class MyOtherClass {

   private:
      int aNumber;

   public:
      MyOtherClass (int someNumber);
      ~MyOtherClass();
      void doSomething();
}

MyOtherClass.cpp

include "MyOtherClass.h"

MyOtherClass::MyOtherClass (int someNumber) {
   aNumber = someNumber;
}

void MyOtherClass::doSomething () {
    std::cout << aNumber;
}
question from:https://stackoverflow.com/questions/31488756/explicitly-initialize-member-which-does-not-have-a-default-constructor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are almost there. When you create an object in C++, by default it runs the default constructor on all of its 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...