Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 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;
}
See Question&Answers more detail:os

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...