您的位置:首页 > 编程语言 > C语言/C++

2012/1/25 《C++ Primer Plus》第十一章:使用类 学习笔记

2012-01-25 13:29 941 查看
《C++ Primer Plus》第十一章学习笔记

118:很多C++(也包括C语言)操作符已经被重载。例如,将*操作符用于地址,将得到存储在这个地址中的值;但将它用于两个数字时,得到的是它们的乘积。

119:重载操作符使代码看起来更自然。重载的操作符必须是有效的C++操作符,例如不能重载@。

120:Don’t return a reference to a local variable or another temporary object. When the function terminatesand the local variable or temporary object disappears, the reference becomes a reference
tonon-existent data.(原文。翻译多次出现“指向”,容易让人混淆指针和引用的概念)

121:P341 一些重载的限制:

1、重载后的操作符必须至少一个操作数是用户定义的类型,这将防止用户为标准类型重载操作符。

2、使用操作符时不能违反操作符原来的句法规则,同样不能修改操作符的优先级。

3、不能定义新的操作符,例如不能定义operator**()来表示求幂。

4、注意一些不能重载的操作符P342。

5、大多数操作符都可以通过成员或非成员函数进行重载,但有4个操作符只能通过成员函数进行重载:= , () , [] , ->。

122:友元有3种:

1、友元函数

2、友元类

3、友元成员函数;

此章只讨论1; 2和3 在15章讨论

123:声明友元函数只需将其原型放在类声明中,并在原型前加上friend,但它不是成员函数,因此不能使用成员操作符来调用,并且它与成员函数的访问权限相同。

124:再次强调:按引用传递使用的内存和时间都比按值传递少。

125:In general, to overload the << operator to display an object of class c_name, you use a friend functionwith a definition in this form:

ostream & operator<<(ostream & os, const c_name & obj)

{

os << ... ; // display object contents

return os;

}

126:只有在类声明的原型中才能使用friend关键字。除非函数是内联的(声明的同时定义),否则不能在函数定义中使用该关键字。

127:类非常适合在一个对象中表示实体的不同方面。然后,编写这样的类函数,以便给一种表达方式赋值时,将自动给其他表达方式赋值。例子见P354的Vector类。

128:如果方法通过计算得到一个新的类对象,则应考虑是否可以使用类构造函数来完成这种工作。这样做不仅可以避免麻烦,而且可以确保新的对象是按照正确的方式创建的。

129:转换函数(conversion functions)是将类对象赋给基本类型时,类调用的函数,注意以下几点:

1、转换函数必须是类方法;

2、转换函数不能指定返回类型;

3、转换函数不能有参数;

例如,转换成double类型的函数原型如下:operator double();

130:关键字explicit不能用于转换函数,若只要显式转换,只需用一个功能相同的非转换函数替换该转换函数即可,但仅在被显式地调用时,该函数才会执行。

131:In summary, C++ provides the following type conversions for classes:

• A class constructor that has but a single argument serves as an instruction for converting a value of the argument type to the class type. For example, the Stonewt class constructor with a type int argument is invoked automatically
when you assign a type int value to a Stonewt object. However, using explicit in the constructor declaration eliminates implicit conversions and allows only explicit conversions.

• A special class member operator function called a conversion function serves as an instruction for converting a class object to some other type. The conversion function is a class member, has no declared return type, has no
arguments, and is called operator typeName(), where typeName is the type to which the object is to be converted. This conversion function is invoked automatically when you assign a class object to a variable of that type or use the type cast operator to that
type.

书中的错误:

P344 倒数一行的+改为*;

P343 “#endif”后多了个点;

P346 第一个函数代码中的参数“m”应该为“mult”;

P366 display函数的原型参数里应该加上“&”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: