#include <iostream>
#include <cstring>
using namespace std;
class Str
{
private:
static int num; // 实例计数器
char *str;
public:
Str(){str=0;} // 指向0,防止delete时程序崩溃!
Str(char *s) // 普通构造函数
{
num ++;
str = new char[strlen(s)+1];
strcpy(str, s);
}
// 深复制 复制构造函数
Str(Str &s)
{
num ++;
str = new char[strlen(s.str)+1];
strcpy(str, s.str);
}
// 深复制 赋值运算符
Str& operator=(Str &s)
{
if (&s==this) // 判断是不是赋值给自己(很重要!)
return *this;
num ++;
delete[] str; // 释放之前str指向的内存(很重要!因此在构造函数中要将str指向某个确定的内存,如果没有,会造成崩溃)
str = new char[strlen(s.str)+1];
strcpy(str, s.str);
return *this;
}
// 返回引用使得可以通过a[1]='a'修改某个字符的值
char& operator[](int i)
{
return str[i];
}
// 只返回值,不允许修改数据
char operator[](int i) const
{
return str[i];
}
void show()
{
cout&
c++ 类的复制构造及赋值运算-练习题
最新推荐文章于 2023-04-10 08:07:16 发布