我编写了下面一段代码
#include <iostream>
using namespace std;
char s0[100]; //A
class CString
{
char* str; //字符串
public:
CString()
{
str = NULL;
}//构造函数
CString(const char s[])
{
char s1[100];
for (int i = 0; i < 100; i++)
{
s1[i] = s[i];
}
str = s1;
}//构造函数
CString(CString& t)
{ //B
for (int i = 0; i < 100; i++)
{
s0[i] = *t.str++;
}
str = s0;
}//拷贝构造函数
~CString()
{
}
int Set(const char s[])
{
char s1[100];
for (int i = 0; i < 100; i++)
{
s1[i] = s[i];
}
str = s1;
return sizeof(s);
}//将str重新赋值为s,返回其长度
void Print()
{
while(*this->str!='\0')
cout << *this->str++;
}//输出
};
int main()
{
char s0[100], s1[100];
cin >> s0 >> s1;
CString cs0(s0), cs1(cs0);
cs0.Set(s1);
cs0.Print();
cs1.Print();
return 0;
}
我将char s0【100】放在A处,输入 abc def 输出是def abc,是我预期的结果
但是将其放在B处,就会输出 def def,这是为啥呢?
因为 s1 是局部变量,离开 {} 作用域就消失了,s0 是全局变量,只要程序运行就存在。需要在内部 用new 分配内存,
#include <iostream>
using namespace std;
char s0[100]; //A
class CString
{
char* str; //字符串
public:
CString()
{
str = NULL;
}//构造函数
CString(const char s[])
{
char *s1 = new char[100]; // 这里用 new 分配内存
for (int i = 0; i < 100; i++)
{
s1[i] = s[i];
}
str = s1;
}//构造函数
CString(CString& t)
{ //B
for (int i = 0; i < 100; i++)
{
s0[i] = *t.str++;
}
str = s0;
}//拷贝构造函数
~CString()
{
}
int Set(const char s[])
{
char *s1 = new char[100]; // 分配内存
for (int i = 0; i < 100; i++)
{
s1[i] = s[i];
}
if (str) // 如果原来有内存 释放内存
{
delete [] str;
}
str = s1;
return sizeof(s);
}//将str重新赋值为s,返回其长度
void Print()
{
while(*this->str!='\0')
cout << *this->str++;
}//输出
};
int main()
{
char s0[100], s1[100];
cin >> s0 >> s1;
CString cs0(s0), cs1(cs0);
cs0.Set(s1);
cs0.Print();
cs1.Print();
return 0;
}
因为你用的局部变量来存储字符串,你构造函数用动态分配内存就不会有这种问题出现