简体   繁体   中英

C++ class member that requires a constructor parameter

I'm getting confused:

Director.cpp

class Director {

  public:
  Director() {

  }

  runScene(Scene _scene) {
    scene = _scene;
  }

  private:
  Scene scene; // <-- Private member "scene" of type Scene.

};

Scene.cpp

class Scene {

  public:
  Scene(int number) {


  }

}

g++ says

no matching function for call to 'Scene::Scene()'

It seems like it is trying to initialise scene , which can't be done because there are no constructors that take no parameters. I'm still new to C++ - why is it trying to initialise that private member?

I'm not sure what is going on. I tried changing Scene scene; to Scene scene(int); , which will just cause runScene to throw an error, because that would make the compiler think that scene is actually a function.

All I want is my class to have a member property of type Scene , which I can change at any time. What am I doing wrong?

By declaring constructor in Scerne

Scene(int number) {

}

you are effectively disabling the default constructor which takes no parameters. You either need to add Scene() (No parameters) constructor to your scene class or your Director constructor needs to look something like this:

Director() : Scene(0)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM