实验目的:
掌握派生类的声明方法和派生类构造函数的定义方法
掌握不同方式下,构造函数和析构函数的执行顺序与构造规则
//原程序
#include <iostream>
#include <string>
using namespace std;
class MyArray {
public:
MyArray(int length);
~MyArray();
void Input();
void Display(string);
protected:
int* alist;
int length;
};
MyArray::MyArray(int leng) {
if (leng <= 0) {
cout << "error length";
exit(1);
}
alist = new int[length];
length = leng;
if (alist == NULL) {
cout << "assign failure";
exit(1);
}
cout << "MyArray类对象已创建!" << endl;
}
MyArray::~MyArray() {
delete[] alist;
cout << "MyArray类对象已撤销!" << endl;
}
void MyArray::Display(string str) {
int i;
int* p = alist;
cout << str << length << "个整数:";
for (i = 0; i < length; i++, p++) {
cout << *p << "";
}
cout << endl;
}
void MyArray::Input() {
cout << "请从键盘输入" << length << "个整数:";
int i;
int* p = alist;
for (i = 0; i < length; i++, p++) {
cin >> *p;
}
}
int main() {
MyArray a(5);
a.Input();
a.Display("显示排序以前已经输入的");
return 0;
}
运行过后,显示结果如上;
析构函数不能正常运行,原因是 构造函数在调用时,leng和length的调用位置不对,应该放在开头。
实验内容:
写出程序运行结果。
声明一个SortArray继承类MyArray,在该类中定义一个函数,具有将输入的整数从小到大进行排序的功能。
#include <iostream>
#include <str