C++ - How do I initialize a constructor of a separate class from the constructor of a class?

↘锁芯ラ 提交于 2020-01-02 03:31:26

问题


Basically what I am trying to achieve is to create a local (and private) instance of the class deltaKinematics in the class geneticAlgorithm

In the geneticAlgorithm.h file I have:

class DeltaKinematics; //class is defined in separate linked files

class GeneticAlgorithm {
  //private  
    DeltaKinematics deltaRobot;

public:

    GeneticAlgorithm(); //constructor

};

This is all fine, but when I go to declare the GeneticAlgorithm constructor, I can't work out how to construct the instance of DeltaKinematics

This is the geneticAlgorithm.cpp constructor:

GeneticAlgorithm::GeneticAlgorithm(){ //The error given on this line is "constructor for 'GeneticAlgorithm' must explicitly initialize the member 'deltaRobot' which does not have a default constructor"

    DeltaKinematics deltaRobot(100); //this clearly isn't doing the trick

    cout << "Genetic Algorithmic search class initiated \n";
}

How do I go about initializing that local instance?


回答1:


Member initializer list:

GeneticAlgorithm::GeneticAlgorithm() : deltaRobot(100) {
}



回答2:


GeneticAlgorithm::GeneticAlgorithm() : deltaRobot(100) {
    cout << "Genetic Algorithmic search class initiated \n";
}

Note the : after the constructor name: it is the beginning of the initialization sequence for the member data variables of the class. They appear as calls to their constructors, with the parameters you want to pass, and should be in the same order they're declared.



来源:https://stackoverflow.com/questions/6055154/c-how-do-i-initialize-a-constructor-of-a-separate-class-from-the-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!