如何在构造函数c ++中初始化多个const变量?

时间:2014-05-24 17:35:20

标签: c++ variables constructor static

标题:

#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
#include "Date.h"
#include "String.h"

class Employee {
private:
    String firstname;
    String lastName;
    const Date birth;
    const int id;
    const Date start;
    double salary;
    int status;
public:
    Employee();
Employee(char* firstname,char* lastname,Date birth,int id,Date start,double salary,int status);
virtual ~Employee();
};

cpp:

#include "Employee.h"
#include "Date.h"
#include "String.h"


Employee::Employee() :id( 0 ) {
    salary=0;
    status=0;
}
Employee::Employee(char* firstname,char* lastname,Date birth,int Id,Date start,double   salary,int status){
}

Employee::~Employee() {

}
#endif /* EMPLOYEE_H_ */

如何初始化构造函数中的所有const变量? (我不能发布到小文本..请注意这个bal bla bla bla bla Bla bla bla bla bla bla bla。)。

1 个答案:

答案 0 :(得分:4)

用于id的初始化方法是构造函数初始化列表的一部分。它是一个列表,因为它可用于初始化多个值,逗号分隔。如果可能的话,您甚至可以使用它来初始化非const成员。

Employee::Employee()
    :birth(args),
     id( 0 ),
     start(args),
     salary(0.0),
     status(0)
{}

请注意,我按照它们在类体中出现的顺序对成员进行了排序。这不是一个要求,但这是一种好的做法,因为这是他们无论如何都会被初始化的顺序,无论你列出它们的顺序如何。如果一个成员的初始化依赖于另一个成员的值,这就变得尤为重要。