类成员的显式初始化

Although most objects are initialized by running an appropriate constructor, it is possible to initialize the data members of simple nonabstract classes directly. Members of classes that define no constructors and all of whose data members are public may be initialized in the same way that we initialize array elements:

尽管大多数对象可以通过运行适当的构造函数进行初始化,但是直接初始化简单的非抽象类的数据成员仍是可能的。对于没有定义构造函数并且其全体数据成员均为 public 的类,可以采用与初始化数组元素相同的方式初始化其成员:

struct Data {
         
int ival;
         
char *ptr;
     };
     
// val1.ival = 0; val1.ptr = 0
     Data val1 = { 00 };

     
// val2.ival = 1024;
     
// val2.ptr = "Anna Livia Plurabelle"
     Data val2 = { 1024"Anna Livia Plurabelle" };

The initializers are used in the declaration order of the data members. The following, for example, is an error because ival is declared before ptr:

根据数据成员的声明次序来使用初始化式。例如,因为 ivalptr 之前声明,所以下面的用法是错误的:

   // error: can't use "Anna Livia Plurabelle" to initialize the int ival
     Data val2 = { "Anna Livia Plurabelle" , 1024 };

This form of initialization is inherited from C and is supported for compatibility with C programs. There are three significant drawbacks to explicitly initializing the members of an object of class type:

这种形式的初始化从 C 继承而来,支持与 C 程序兼容。显式初始化类类型对象的成员有三个重大的缺点。

  1. It requires that all the data members of the class be public.

    要求类的全体数据成员都是 public

  2. It puts the burden on the programmer to initialize every member of every object. Such initialization is tedious and error-prone because it is easy to forget an initializer or to supply an inappropriate initializer.

    将初始化每个对象的每个成员的负担放在程序员身上。这样的初始化是乏味且易于出错的,因为容易遗忘初始化式或提供不适当的初始化式。

  3. If a member is added or removed, all initializations have to be found and updated correctly.

    如果增加或删除一个成员,必须找到所有的初始化并正确更新。


It is almost always better to define and use constructors. When we provide a default constructor for the types we define, we allow the compiler to automatically run that constructor, ensuring that every class object is properly initialized prior to the first use of that object.

定义和使用构造函数几乎总是较好的。当我们为自己定义的类型提供一个默认构造函数时,允许编译器自动运行那个构造函数,以保证每个类对象在初次使用之前正确地初始化。

Exercises Section 12.4.5

The data members of pair are public, yet this code doesn't compile. Why?

pair 的数据成员为 public,然而下面这段代码却不能编译,为什么?

     pair<int, int> p2 = {0, 42}; // doesn't compile, why? 
解答:对于没有定义构造函数并且其全体数据成员均为 public 的类,可以采用与初始化数组元素相同的方式初始化其成员。

posted on 2011-07-06 14:04 Smart Pointer 阅读(468) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


<2011年7月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿

随笔档案

收藏夹

搜索

最新评论

阅读排行榜

评论排行榜