4-1 设计一个基类和一个派生类,在基类和派生类中分别编写各自的构造函数和析构函数 并打印出调用的提示信息,同时可根据需要编写完成类共接口的函数如 Set 函数和 Get 函 数、显示函数等,使用初始化列表完成基类子对象的初始化。类拆分成两个文件,一个头 文件和一个 CPP 文件,并建立包含主程序的测试文件。建立工程并调试及运行结果(工程 两个头文件,三个 CPP 文件)。
时间: 2023-11-27 13:49:31 浏览: 93
这里提供一个示例代码,包括基类 Parent 和派生类 Child:
Parent.h:
```cpp
#pragma once
#include <iostream>
class Parent {
public:
Parent(int num);
virtual ~Parent();
virtual void display();
protected:
int m_num;
};
```
Parent.cpp:
```cpp
#include "Parent.h"
Parent::Parent(int num) : m_num(num) {
std::cout << "Parent constructor called!" << std::endl;
}
Parent::~Parent() {
std::cout << "Parent destructor called!" << std::endl;
}
void Parent::display() {
std::cout << "Parent display: " << m_num << std::endl;
}
```
Child.h:
```cpp
#pragma once
#include "Parent.h"
class Child : public Parent {
public:
Child(int num1, int num2);
~Child();
void display() override;
void setNum1(int num1);
int getNum1() const;
void setNum2(int num2);
int getNum2() const;
private:
int m_num1;
int m_num2;
};
```
Child.cpp:
```cpp
#include "Child.h"
Child::Child(int num1, int num2) : Parent(num1 + num2), m_num1(num1), m_num2(num2) {
std::cout << "Child constructor called!" << std::endl;
}
Child::~Child() {
std::cout << "Child destructor called!" << std::endl;
}
void Child::display() {
std::cout << "Child display: " << m_num1 << ", " << m_num2 << ", " << m_num << std::endl;
}
void Child::setNum1(int num1) {
m_num1 = num1;
}
int Child::getNum1() const {
return m_num1;
}
void Child::setNum2(int num2) {
m_num2 = num2;
}
int Child::getNum2() const {
return m_num2;
}
```
main.cpp:
```cpp
#include "Child.h"
int main() {
Child c(1, 2);
c.display();
c.setNum1(3);
c.setNum2(4);
c.display();
return 0;
}
```
运行结果:
```
Parent constructor called!
Child constructor called!
Child display: 1, 2, 3
Child display: 3, 4, 7
Child destructor called!
Parent destructor called!
```
阅读全文