C++类的继承

来源:互联网 发布:女朋友性格太强势 知乎 编辑:程序博客网 时间:2024/05/16 01:13

#include<iostream>
#include<string>
using namespace std;

class B1
{
char *a;
protected:
 B1(): a(0){}  //只能由本类及派生类调用
public:
~B1()
{
delete []a;
cout << "B1 ";
}
void Output()
{
cout << a << endl;
}
void Seta(char *aa)
{
delete []a;
a = new char[strlen(aa) + 1];
strcpy(a, aa);
}
};

class B2:public B1
{
char* b;
public:
B2():b(0){}
~B2()
{
delete []b;
cout << "B2";
}
void Output()
{
B1::Output();
cout << b << endl;
}

void Setb(char *aa, char* bb)
{
Seta(aa);
delete []b;
b = new char[strlen(bb) + 1];
strcpy(b, bb);
}
};

void Input(B2* &r, int n)
{
r = new B2[n];
char a[20], b[20];

for (int i = 0; i < n; i++)
{
cout << "Input two strings:";
cin >> a >> b;
r[i].Setb(a, b);
}
}

void main()
{
B2* a = NULL;
int n = 3;
Input(a, n);
for (int i = 0; i < n; ++i)
{
a[i].Output();
}
delete []a;
cout << endl << sizeof(B2) << endl;
}