gpt4 book ai didi

c++ - 构造函数初始化

转载 作者:行者123 更新时间:2023-11-30 00:36:39 24 4
gpt4 key购买 nike

我正在阅读 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 and final, the other data members are initialized implicitly. Specifically, n is initialized by the string default constructor, and homework is initialized by the vector 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) {}

我只想澄清一下,这意味着像 intdouble 这样的东西在term 需要专门初始化吗?

最佳答案

没错。
但是 std::不是您要找的。

任何基本类型都不会被初始化,除非您明确地进行初始化。

所以 char/int/float/pointers等。另外(正如下面 Ian 所指出的)任何没有显式构造函数的类/union 将默认初始化其成员(这意味着基本的(并且对于没有显式构造函数的类/union 的成员是递归的)它们是未定义的)。

旁注:

  • 此规则适用于自动和动态存储持续时间对象
  • 静态和线程存储持续时间对象为零初始化。

关于c++ - 构造函数初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15564319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com