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

how to initialize more than one const variable in a constructor c++?

本文关键字:const 变量 初始化 构造函数      更新时间:2023-10-16

#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变量?

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

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

注意,我按照成员在类体中出现的顺序排列了成员。这不是必需的,但这是一个很好的实践,因为无论如何,这就是它们初始化的顺序,无论您以什么顺序列出它们。如果一个成员的初始化依赖于另一个成员的值,这一点尤为重要。