C ++ - 如何从类的构造函数初始化单独类的构造函数?

时间:2011-05-19 07:21:19

标签: c++ class constructor initialization

基本上我想要实现的是在类deltaKinematics中创建类geneticAlgorithm的本地(和私有)实例

在我的geneticAlgorithm.h文件中:

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

class GeneticAlgorithm {
  //private  
    DeltaKinematics deltaRobot;

public:

    GeneticAlgorithm(); //constructor

};

这很好,但是当我去声明GeneticAlgorithm构造函数时,我无法弄清楚如何构造DeltaKinematics的实例

这是geneticAlgorithm.cpp构造函数:

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";
}

如何初始化该本地实例?

2 个答案:

答案 0 :(得分:12)

会员初始化人名单:

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

答案 1 :(得分:3)

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

注意构造函数名后面的::它是类的成员数据变量的初始化序列的开始。它们显示为对其构造函数的调用,具有您想要传递的参数,并且应该与它们声明的顺序相同。