#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()
{
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("显示已输入的");
return0;
}
加入排序后:
#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()
{
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;
}
class SortArray : public MyArray {
public:
SortArray(int a) :MyArray(a) {};
void paixv();
void show();
};
void SortArray::paixv() {
int a, b, c, * p = alist;
for (a = 0; a <= length - 1; a++) {
for (b = 0; b <= a; b++) {
if (p[a] <= p[b]) {
c = p[b];
p[b] = p[a];
p[a] = c;
}
}
}
}
void SortArray::show()
{
int i;
int* p = alist;
for (i = 0; i < length; i++, p++)
cout << *p << " ";
cout << endl;
}
int main()
{
SortArray b(5);
b.Input();
b.paixv();
b.show();
return 0;
}
心得体会:本次实验用到了类与对象的继承,继承时要注意用到的数据为父类的保护成员。从中可以看出,数据成员一般不会设为共有,但如果要想让子类继承使用,可设为保护成员。在实验代码中,析构函数用到了delete语句,但在此次实验由于没有创建堆区,所以无需删除。