- 构造函数是特殊的成员函数
- 在冒号和花括号之间的代码称为构造函数的初始化列表
- 如果没有为一个类显式定义任何构造函数,编译器将自动为这个类生成默认构造函数
- const 成员函数不能修改调用该函数的对象,只能读取而不能修改调用它们的对象的数据成员
why?const成员函数的this指针被隐含地修改为const Sales_item *const this的形式, 故其数据成员(是通过this调用的)不能被修改
const对象只能调用const成员函数,非const对象可以调用const成员函数或非const成员函数
why?const对象的成员是不能被修改的,如果调用非const成员函数,则可以通过该函数可以修改数据成员,这是矛盾的;
非const对象本身可以修改其成员,所以调用const和非const都无所谓,不会产生矛盾
"The purpose of that const is to modify the type of the implicit this pointer.
However, this is implicit and does not appear in the parameter list. There is noplace to indicate that this should be a pointer to const.
The language resolves this problem by letting us put const after the parameter list of a member function"
const函数的实质是修改this的类型,因为不能显式地修改this指针的类型,只能通过在函数后面加上const修饰符来实现这一功能了 - 对于类中的const和引用数据成员,如何初始化
1 // error: ci and ri must be initialized 2 ConstRef::ConstRef(int ii) 3 { // assignments: 4 i = ii; // ok 5 ci = ii; // error: cannot assign to a const 6 ri = i; // error: ri was never initialized 7 }
1 // ok: explicitly initialize reference and const members 2 ConstRef::ConstRef(int ii): i(ii), ci(ii), ri(i) { }
We must use the constructor initializer list to provide values for members thatare const, reference, or of a class type that does not have a default
constructor