(1)赋值函数的书写步骤:
a.判断是否是自身赋值;
b.释放原有空间;
c.开辟新空间并赋新值;
d.返回自身对象;
eg:
String& operator=(const String &str)
{
cout<<"Assign: "<<this<<endl;
//(1)判断是否是自身赋值
if(this != &str){
free(data); //(2)释放原有空间
//(3)开辟新空间并赋值
data = (char *)malloc(strlen(str.data) + 1);
strcpy(data, str.data);
}
//(4)返回自身对象
return *this;
}
(2)拷贝构造函数:
String(const String &str)
{
cout<<"copy create"<<endl;
data = (char *)malloc(strlen(str.data) + 1);
strcpy(data, str.data); //一般还会用到memcpy函数
}
(3)C和C++的区别
(4)c++中的const
A.
int main()
{
const int a = 10;
int b = 20;
//const int *p 与 int const *p 是一样的道理
const int * p = &a; //p可以改变,但*p不可以改变(*p为常量)
//*p = 100;
p = &b; //p可以改变,因为p不是常量(const)
return 0;
}
[root@localhost Test4_2]# g++ test1.cpp -o test1
test1.cpp: In function ‘int main()’:
test1.cpp:75:7: error: assignment of read-only variable ‘p’
p = &b;
^
B.
int main()
{
//const int a = 10; //将int *const p改为const int * const p 也可以
int a = 10;
int b = 20;
int * const p = &a; //p不可以改变,但*p可以改变(*p不为常量)
*p = 100; //*p可以改变(不是常量const)
//p = &b; //p不可以改变,因为p是常量(const)
return 0;
}
[root@localhost Test4_2]# g++ test1.cpp -o test1
test1.cpp: In function ‘int main()’:
test1.cpp:73:23: error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive]
int * const p = &a; //p不可以改变,但*p可以改变(*p不为常量)
^
test1.cpp:75:7: error: assignment of read-only variable ‘p’
p = &b; //p不可以改变,因为p是常量(const)
^
[root@localhost Test4_2]#
C.
int main()
{
const int a = 10;
//int a = 10;
int b = 20;
const int * const p = &a; //p不可以改变,但*p也不可以改变(*p和p都为常量)
*p = 100; //*p不可以改变(是常量const)
p = &b; //p不可以改变,因为p是常量(const)
return 0;
}
[root@localhost Test4_2]# g++ test1.cpp -o test1
test1.cpp: In function ‘int main()’:
test1.cpp:75:8: error: assignment of read-only location ‘*(const int*)p’
*p = 100; //*p不可以改变(是常量const)
^
test1.cpp:76:7: error: assignment of read-only variable ‘p’
p = &b; //p不可以改变,因为p是常量(const)
^
[root@localhost Test4_2]#
(5)输出流是否可以重载为类的成员函数
答:从语法上是可以的,但是调用的时候需要用对象调用cout,那么输出方式就会与习惯不同,习惯上是:cout<<i;
;但是将其重载为类的成员函数后的输出就变为:i<<cout;
;所以一般将输出流重载为友元函数
(6)++运算符的重载
前置++:
Int& operator++() //前置++没有参数
{
i++;
return *this; //返回对象的引用(即就是对象的地址)
}
后置++
//后置++有参数
A.
Int operator++(int)
{
Int tmp(i); //定义临时变量(此处调用的是类Int的构造函数)
i++;
return tmp; //返回临时变量
}
B.
Int operator++(int)
{
Int tmp(*this); //定义临时变量(此处调用类Int的拷贝构造函数)
i++;
return tmp;
}
(6)空指针可以无限制释放,没有影响
(7)*缓冲区在内核的内存区
*