c++ - 构造函数初始化

标签 c++ class constructor

我正在阅读 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/

相关文章:

c++ - 在 C/C++ 中直接写入内存地址的最短代码是什么?

c++ - 为什么我的缓冲区占用的字节数超过允许的字节数?

c++ - C++ 类中动态位集的声明和赋值

java - 奇怪的复制构造函数

带有日期的 c++ to_string 错误

c# - 为什么在面向对象设计中某些模式的类具有单独的数据类

java - 为什么我不能在第一个条件中使用类型检查变量作为第二个条件中的类型转换变量?

c++ - Dlib:如何初始化一个忽略标志设置为 1 的 mmod_rect?

c++ - 使用析构函数后,代码显示 "reference to Book::~Book()"错误

C++ 对象未声明标识符