都是类的继承问题
#include <iostream>
#include <cstring>
using namespace std;
class CStrOne
{
protected:
char* str1;
public:
CStrOne(const char* p)
{
size_t len = strlen(p) + 1;
str1 = new char[len];
strcpy_s(str1, len, p);
}
~CStrOne()
{
if (str1) delete[] str1; str1 = 0;
}
//获取字符串
char* getStr1() { return str1; }
//显示内容
void show() { cout << str1 << endl; }
};
class CStrTwo :public CStrOne
{
private:
char* str2;
public:
CStrTwo(const char* p1, const char* p2) :CStrOne(p1)
{
size_t len = strlen(p2) + 1;
str2 = new char[len];
strcpy_s(str2, len, p2);
}
~CStrTwo()
{
if (str2) delete[] str2; str2 = 0;
}
void strCat()
{
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
size_t len = len1 + len2 + 1;
char* ptr = new char[len];
strcpy_s(ptr, len, str1);
strcat_s(ptr, len, str2);
ptr[len - 1] = 0;
cout << ptr << endl;
if(ptr) delete[] ptr;
ptr = 0;
}
};
int main()
{
char buf1[100], buf2[100], buf3[100];
cout << "请输入一个字符串来构造CStrOne的实例:" << endl;
cin.getline(buf1, 100);
CStrOne str1(buf1);
cout << "调用CStrOne的显示函数显示字符串的内容:"<<endl;
str1.show();
cout << "请输入两个字符串来构造CStrOne的实例(一行一个):" << endl;
cin.getline(buf2,100);
cin.getline(buf3, 100);
CStrTwo str2(buf2,buf3);
cout << "调用CStrTwo的合并函数合并两个字符串并显示:" << endl;
str2.strCat();
return 0;
}
都是一个套路
对于字符串类的派生问题,可以考虑使用多继承的方法,将字符串类派生为其他需要用到字符串的类的父类。
具体的实现方法如下:
class String {
public:
String(const char* str) {
// 实现字符串类的构造函数
}
// 实现其他字符串操作方法
};
class Parent {
public:
Parent() {
// 父类的构造函数
}
// 父类的其他成员函数
};
class Child : public Parent, public String {
public:
Child(const char* str) : String(str) {
// 子类的构造函数,需要调用基类的构造函数
}
// 子类的其他成员函数
};
这样就可以将字符串类作为子类的一部分,让子类继承其实现的字符串操作方法。在实例化子类对象时,需要调用父类和基类的构造函数,分别初始化它们的成员。