博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++类的继承
阅读量:4106 次
发布时间:2019-05-25

本文共 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/

你可能感兴趣的文章
(python版)《剑指Offer》JZ01:二维数组中的查找
查看>>
(python版)《剑指Offer》JZ06:旋转数组的最小数字
查看>>
(python版)《剑指Offer》JZ13:调整数组顺序使奇数位于偶数前面
查看>>
(python版)《剑指Offer》JZ28:数组中出现次数超过一半的数字
查看>>
(python版)《剑指Offer》JZ30:连续子数组的最大和
查看>>
(python版)《剑指Offer》JZ02:替换空格
查看>>
JSP/Servlet——MVC设计模式
查看>>
使用JSTL
查看>>
Java 8新特性:Stream API
查看>>
管理用户状态——Cookie与Session
查看>>
最受欢迎的前端框架Bootstrap 入门
查看>>
JavaScript编程简介:DOM、AJAX与Chrome调试器
查看>>
通过Maven管理项目依赖
查看>>
通过Spring Boot三分钟创建Spring Web项目
查看>>
Spring的IoC(依赖注入)原理
查看>>
Java编程基础:static的用法
查看>>
Java编程基础:抽象类和接口
查看>>
Java编程基础:异常处理
查看>>
Spring MVC中使用Thymeleaf模板引擎
查看>>
Spring处理表单提交
查看>>