构造函数初始化 [英] Constructor initialization

查看:148
本文介绍了构造函数初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读Andrew Koenig和Barbara E. Moo的Accelerated C ++,我在关于构造函数的章节(5.1)。




我们说构造函数的存在是为了确保创建的对象的数据成员处于明智的状态。一般来说,这个设计目标意味着每个构造函数都应该初始化每个数据成员。给成员一个价值的需要对于内置类型的成员尤其关键。 ...



虽然我们只明确初始化了 midterm final ,其他数据成员被隐式初始化。具体来说, n string 默认构造函数和家庭作业向量默认构造函数初始化。


  class Student_info {
public:
std :: string name()const n;}
bool valid()const {return!homework.empty();}
std :: istream& read(std :: istream&);

()const;
private:
std :: string n;
double midterm,final;
std :: vector< double> homework;
};

,其默认构造函数为

  Student_info :: Student_info():midterm(0),final(0){} 

我想澄清一下,这意味着 int double std :: 之前,需要对其进行初始化。

解决方案

这是正确的。

但是std ::不是你正在寻找的。

任何基本类型都不会初始化,除非你它显式。



所以 char / int / float / pointers 没有显式构造函数的类/联合会默认初始化它的成员(这意味着基本的(对于没有和显式构造函数的类/联合的成员递归),它们是未定义的。)



附注:




  • 此规则适用于自动和动态储存期间物件

  • 静态和线程存储持续时间对象已初始化为零。


I am reading "Accelerated C++" by Andrew Koenig and Barbara E. Moo, and I'm at the chapter about constructors (5.1).

They mention here that

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.

The class they are talking about is

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;
};

and their default constructor is

Student_info::Student_info(): midterm(0), final(0) {}

I would just like to clarify that this means that things like int and double where there isn't a std:: before the term will need to be initialized specifically?

解决方案

That is correct.
But std:: is not what you are looking for.

Any of the fundamental types are not initialized unless you do it explicitly.

So char/int/float/pointers etc. Also (as noted by Ian below) any class/unions without an explicit constructor will default initialize its members (which means fundamental (and recursively for member s of class/unions without and explicit constructor) that they are left undefined).

A side note:

  • This rules applies to automatic and dynamic storage duration objects
  • Static and thread storage duration objects are zero initialized.

这篇关于构造函数初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆