#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);
}
length = leng;
alist = new int[length];
if (alist == NULL)
{
cout << "assign failure";
exit(1);
}
cout<<"MyArrayl类对象已创建!" << 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;
}
运行结果:
#include<iostream>
#include<string>
using namespace std;
class MyArray {
public:
MyArray(int length);
~MyArray();
void Input();
void Display(string);
protected:
int* alist;
int length;
};
class SortArray :public MyArray
{
public:
SortArray(int leng) :MyArray(leng)
{
cout << "SortArray类对象已创建!" << endl;
}
~SortArray()
{
cout << "SortArray类对象已销毁!" << endl;
}
void sort()
{
int i, k, temp;
int* p = alist;
cout << "显示排序以后的5个整数:";
for (i = 0; i < length - 1; i++)
for (k = i + 1; k < length; k++)
{
if (*(alist + i) > *(alist + k))
{
temp = *(alist + i);
*(alist + i) = *(alist + k);
*(alist + k) = temp;
}
}
for (i = 0; i < length; i++, p++)
{
cout << *p << " ";
}
cout << endl;
}
};
MyArray::MyArray(int leng) {
if (leng <= 0)
{
cout << "error length";
exit(1);
}
length = leng;
alist = new int[length];
if (alist == NULL)
{
cout << "assign failure";
exit(1);
}
cout << "MyArrayl类对象已创建!" << 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()
{
SortArray a(5);
a.Input();
a.Display("显示已经输入的");
a.sort();
return 0;
}
运行结果:
总结:
派生类构造函数和析构函数的执行顺序: ? ? ?创建派生类对象时,先执行基类的构造函数,然后再执行派生类的构造函数;当撤销派生类对象时,先执行派生类的析构函数,再执行基类的析构函数。
构造函数的执行顺序是:先调用基类构造函数,后调用派生类的构造函数,析构函数的调用顺序和构造函数的调用顺序正好相反。
|