using namespace std; class Base1 { public: //下列语句需要声明纯虚函数Show ▁▁▁(3分); }; class Base2 { protected: char * _p; Base2(const char *s) { _p = new char[strlen(s) + 1]; //下列语句将形参指向的字符串常量复制到该类的字符数组中 ▁▁▁(3分); } ~Base2() { delete [] _p; } }; //Derived类公有继承Base1,私有继承Base2类 class Derived :▁▁▁(3分) { public://以下构造函数调用Base2类构造函数 Derived(const char *s) :▁▁▁(3分) { } void Show() { cout << _p << endl; } }; int main() { Base1 *pb = new Derived("I'm a derived class."); pb->Show(); delete pb; return 0; }
时间: 2024-03-10 13:44:05 浏览: 134
C++ using namespace std 用法深入解析
5星 · 资源好评率100%
完整代码如下:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
class Base1 {
public:
virtual void Show() = 0;
};
class Base2 {
protected:
char *_p;
Base2(const char *s) {
_p = new char[strlen(s) + 1];
strcpy(_p, s);
}
~Base2() { delete [] _p; }
};
class Derived : public Base1, private Base2 {
public:
Derived(const char *s) : Base2(s) {}
void Show() { cout << _p << endl; }
};
int main() {
Base1 *pb = new Derived("I'm a derived class.");
pb->Show();
delete pb;
return 0;
}
```
输出结果为:
```
I'm a derived class.
```
在此程序中,类Base1中声明了纯虚函数Show(),因此该类为抽象基类。类Base2中定义了一个字符数组_p,并在构造函数中对其进行了初始化。类Derived公有继承自Base1和私有继承自Base2。在类Derived的构造函数中调用了Base2的构造函数,将形参指向的字符串常量复制到_p所指向的字符数组中。在类Derived中重写了Show()函数,输出_p所指向的字符串常量。在主函数中,我们首先创建了一个Derived类的对象,并将其转化为Base1类的指针。由于Base1类中声明了纯虚函数Show(),因此Derived类必须实现该函数。在调用pb->Show()时,输出"I'm a derived class."。最后,我们释放了pb所指向的内存空间。
阅读全文