如何在构造函数中初始化多个const变量
how to initialize more than one const variable in a constructor c++?
#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)
{}
注意,我按照成员在类体中出现的顺序排列了成员。这不是必需的,但这是一个很好的实践,因为无论如何,这就是它们初始化的顺序,无论您以什么顺序列出它们。如果一个成员的初始化依赖于另一个成员的值,这一点尤为重要。
相关文章:
- 在内存不足之前,我可以声明多少个 const 变量?
- 当设置为 const 变量时使用 nullptr
- 声明与 const 变量和成员函数相同的标识符
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 在成员函数之间传递const变量为数组的索引
- 为什么静态常量字符 * const 变量在为左值时可绑定到右值引用参数
- C 编译器可以执行用于返回值的命名const变量的RVO
- 如何访问一系列const变量作为const数组
- C 错误C3892:您无法分配const变量
- 是否可以在C++中推迟 const 变量的初始化,例如 Java 的"blank final"功能?
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 使用非const变量代替所需的const变量(C )
- 使用const变量时,非静态数据成员的使用无效
- 定义,初始化全局const变量是安全的吗?
- const vs non-const变量一旦分配就没有变化
- 为什么设置const变量(将以相同的值存储)会导致不同的结果
- CPP中的私有静态常规成员变量与const变量
- 在避免新分配的同时,const变量的复杂初始化
- 如何通过其地址更改const变量的值