实验6.1

#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语句,但在此次实验由于没有创建堆区,所以无需删除。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值