1. 《inside the cpp object model》读书笔记

by huangyi

1.1. Object Lessons

  • 除去虚函数,除去构造、析构中编译器自动生成的东西,class和struct的语义是何其的相似。
  • 区分:

   1     Book book;
   2     Library_materials thing1 = book;//拷贝语义
   3     thing1.check_in();//Library_materials::check_in
   4     Library_materials &thing2 = book;//创建别名
   5     thing2.check_in();//Book::check_in
  • 动态语言和c++的重要区别:
    • 类型推导发生时机:编译期/运行期, 虚函数是让c++编译器通过运行时计算(迟绑定)来换取编程灵活性的机制,貌似也是唯一一个。
  • 从纯面向对象语言(java、c#等,也包括delphi)转到c++要注意的是:
    • 区别类引用与类变量,因为这些语言都是只存在类引用的。

   1 TheClass aClass;
  • 同样一句话,前者会解释成类引用,后者解释成类变量。
    • 在处理多态的时候尤其要注意,看下面这段程序:

   1         // class Book : public Library_materials { ...}; 
   2         Book book; 
   3 
   4         // Oops: thing1 is not a Book! 
   5         // Rather, book is ``sliced'' ?
   6         // thing1 remains a Library_materials 
   7         thing1 = book; 
   8 
   9         // Oops: invokes 
  10         // Library_materials::check_in() 
  11         thing1.check_in(); 
  12 
  13         // OK: thing2 now references book 
  14         Library_materials &thing2 = book; 
  15 
  16         // OK: invokes Book::check_in() 
  17         thing2.check_in();

1.2. The Semantics of Constructors

  • 编译器会背着我们干一些事情

1.2.1. Default Constructor Construction

  • between the needs of the program and the needs of the implementation
    • 编译器在后台自动合成默认构造函数的原则是满足the needs of the implementation即可,也就是说目的只是保证程序是个合法的程序而已。所以给成员变量赋初值这样的事情就不会干了。 而 the needs of the program 应该由程序员自己处理。

huangyi/2006-06-05.