参照我的上一个问题,试定义一个CString的子类CString2(可对CString声明做少量调整),CString2声明如下: class CString2 :public CString { public: CString2(); //构造函数 CString2(const char s[]); //构造函数 CString2(CString2& t); //拷贝构造函数 CString2 &Cat(CString2&t); //字符串连接 int Cmp(CString2& t); //字符串比较 }; 在如下主函数中对该类进行测试。 int main() { char s0[100], s1[100]; cin >> s0 >> s1; CString2 cs0(s0),cs1(cs0); cs0.Set(s1); cout << cs0.Cmp(cs1) << endl; CString2 &t=cs0.Cat(cs1); t.Print(); return 0; } 输入输出示意如下: ASDF BSDF 1 BSDFASDF 请在答题窗口录入编写的完整程序。
时间: 2024-01-25 15:02:15 浏览: 84
```
#include<iostream>
#include<cstring>
using namespace std;
class CString {
private:
char* str;
public:
CString();
CString(const char s[]);
CString(CString& t);
~CString();
void Set(const char s[]);
void Print();
};
CString::CString() {
str = new char[1];
str[0] = '\0';
}
CString::CString(const char s[]) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
CString::CString(CString& t) {
str = new char[strlen(t.str) + 1];
strcpy(str, t.str);
}
CString::~CString() {
delete[] str;
}
void CString::Set(const char s[]) {
delete[] str;
str = new char[strlen(s) + 1];
strcpy(str, s);
}
void CString::Print() {
cout << str << endl;
}
class CString2 :public CString {
public:
CString2();
CString2(const char s[]);
CString2(CString2& t);
CString2& Cat(CString2&t);
int Cmp(CString2& t);
};
CString2::CString2() {}
CString2::CString2(const char s[]) :CString(s) {}
CString2::CString2(CString2& t) :CString(t) {}
CString2& CString2::Cat(CString2&t) {
char* temp = new char[strlen(str) + strlen(t.str) + 1];
strcpy(temp, str);
strcat(temp, t.str);
delete[] str;
str = temp;
return *this;
}
int CString2::Cmp(CString2& t) {
return strcmp(str, t.str);
}
int main() {
char s0[100], s1[100];
cin >> s0 >> s1;
CString2 cs0(s0), cs1(cs0);
cs0.Set(s1);
cout << cs0.Cmp(cs1) << endl;
CString2& t = cs0.Cat(cs1);
t.Print();
return 0;
}
```
阅读全文