本文共 828 字,大约阅读时间需要 2 分钟。
#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;}
转载地址:http://cpjsi.baihongyu.com/