我正在阅读 Andrew Koenig 和 Barbara E. Moo 合着的“Accelerated C++”,我正在阅读有关构造函数 (5.1) 的章节。
他们在这里提到
We said that constructors exist to ensure that objects are created with their data members in a sensible state. In general, this design goal means that every constructor should initialize every data member. The need to give members a value is especially critical for members of built-in type. ...
Although we explicityly initialized only
midterm
andfinal
, the other data members are initialized implicitly. Specifically,n
is initialized by thestring
default constructor, andhomework
is initialized by thevector
default constructor.
他们说的类是
class Student_info {
public:
std::string name() const (return n;}
bool valid() const {return !homework.empty();}
std::istream& read(std::istream&);
double grade() const;
private:
std::string n;
double midterm, final;
std::vector<double> homework;
};
它们的默认构造函数是
Student_info::Student_info(): midterm(0), final(0) {}
我只想澄清一下,这意味着像 int
和 double
这样的东西在term 需要专门初始化吗?
最佳答案
没错。
但是 std::不是您要找的。p>
任何基本类型都不会被初始化,除非您明确地进行初始化。
所以 char/int/float/pointers
等。另外(正如下面 Ian 所指出的)任何没有显式构造函数的类/union 将默认初始化其成员(这意味着基本的(并且对于没有显式构造函数的类/union 的成员是递归的)它们是未定义的)。
旁注:
- 此规则适用于自动和动态存储持续时间对象
- 静态和线程存储持续时间对象为零初始化。
关于c++ - 构造函数初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15564319/