qfedu-cpp-level/day5/homework/h1.cpp

85 lines
1.6 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个名为 String 的类,表示字符串。重载赋值运算符 = ,使其能够执行字符串的赋值操作。
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class String
{
private:
char *str;
public:
String(const char *s = NULL) // 构造函数: 默认参数为NULL表示构造一个空字符串
{
if (s == NULL)
str = NULL;
else
{
str = new char[strlen(s) + 1];
strcpy(str, s);
}
}
String(const String &s)
{
if (s.str == NULL)
str = NULL;
else
{
str = new char[strlen(s.str) + 1];
strcpy(str, s.str);
}
}
~String()
{
if (str != NULL) // 如果str不为空删除str
delete[] str;
}
public:
String &operator=(const String &s)
{
if (str == s.str)
return *this;
if (str != NULL) // 如果str不为空则先删除str
delete[] str; // 删除的目的是为了防止内存泄漏
if (s.str == NULL) // 如果s.str为空则str也为空
str = NULL;
else
str = new char[strlen(s.str) + 1]; // +1 是为了存放'\0'
strcpy(str, s.str);
return *this; // 返回当前对象的引用
}
void print()
{
if (str != NULL)
cout << str << endl;
else
cout << "NULL" << endl;
}
};
int main()
{
String s1("hello");
s1.print();
String *s2 = new String("world");
s2->print();
s1 = "xi'an";
s2 = &s1;
s2->print();
return 0;
}