《C++ Primer Plus(第六版)中文版》和源代码
《C++ Primer Plus(第六版)中文版》和源代码
- 美 Stephen Prata 著
- 张海龙 袁国忠 译
- 人民邮电出版社
下载地址
链接:《C++ Primer Plus(第六版)中文版》和源代码
提取码:eb8q
书中含糊不清的知识
关于struct和class的区别
struct和class很相似。虽然class完全涵盖struct的功能,但依旧设立了struct关键字。
因为c++为了兼容c,而struct正是c的功能,所以c++也增加了对struct的支持,同时还扩展了struct的功能。
在使用中,不推荐struct,因为有些功能和struct息息相关,却不能用struct实现,必须要class。比如赋值运算符重载。
模板函数的参数不能自动类型转换
比如:
void test(T a, T b)
{return;}
main()
{
char a=1;
int b=2;
test(1, 2);
}
虽然char可以转换成int,但是这种情况会导致报错,报错内容:参数不明确,可能是char,可能是int。
赋值运算符重载
书中提到,赋值运算符的重载函数必须是成员函数。
赋值运算符重载函数的使用方式可以等效成:
等于号左侧的变量.赋值运算符重载函数(等于号右侧的变量)
。
并且返回值要这样写:return *this;
。
有些运算符重载函数作为成员函数时,会对函数使用const修饰符,但是赋值运算符的重载函数不能用,因为要修改返回值。
示例:
class num
{
public:
char* n = nullptr;
streamoff len = 0;
num& operator=(const num& a)
{
char* t;
if (a.len > 0)
{
len = a.len;
t = new char[a.len];
RtlCopyMemory(t, a.n, sizeof(char) * a.len);
delete n;
n = t;
}
if (a._len > 0)
{
_len = a._len;
t = new char[a._len];
RtlCopyMemory(t, a._n, sizeof(char) * a._len);
delete _n;
_n = t;
}
return *this;
}
};