【问题标题】:how to initialize more than one const variable in a constructor c++?如何在构造函数 C++ 中初始化多个 const 变量?
【发布时间】:2014-05-24 17:35:20
【问题描述】:

标题:

#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)。

【问题讨论】:

  • 和你初始化第一个一样吗?
  • @juanchopanza:这不是重复的。 OP 似乎知道初始化列表,但没有意识到它是一个列表,可用于初始化多个成员。您标记的重复项也不显示。
  • 查看本教程的初始化列表。 cprogramming.com/tutorial/initialization-lists-c++.html
  • @BenjaminLindley 我在 OP 的帖子中没有看到任何证据表明他们知道初始化列表。
  • @juanchopanza:他在他的默认构造函数中使用它。

标签: c++ variables constructor static


【解决方案1】:

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

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

请注意,我已经按照它们在类主体中出现的顺序对成员进行了排序。这不是一项要求,而是一种很好的做法,因为无论如何这是它们的初始化顺序,无论您以什么顺序列出它们。如果一个成员的初始化依赖于另一个成员的值,这一点就变得尤为重要。

【讨论】:

  • 还有基类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 2015-02-19
  • 1970-01-01
  • 2014-05-19
  • 2010-11-28
相关资源
最近更新 更多