C++数组类的自实现,使其可以保存学生成绩,并进行降序排列

类的封装

cpp 复制代码
#ifndef ARRAY_H
#define ARRAY_H

class DoubArray
{
private:
    int m_length;
    double* m_pointer;

public:
    DoubArray(int len);
    DoubArray(const DoubArray& obj);
    int length();
    bool get(int index, double& value);
    bool set(int index, double value);
    void sort(const DoubArray& obj);
    void show(const DoubArray& obj);
    ~DoubArray();
};

#endif // ARRAY_H

类的实现

cpp 复制代码
#include "Array.h"
#include <iostream>
using namespace std;

//构造函数,用于创建数组并初始化
DoubArray::DoubArray(int len)
{
    m_pointer = new double[len];

    for(int i = 0; i < len; i++)
    {
        m_pointer[i] = 0;
    }

    m_length = len;
}

//拷贝构造函数,用于深拷贝
DoubArray::DoubArray(const DoubArray& obj)
{
    m_length = obj.m_length;

    m_pointer = new double[obj.m_length];

    for(int i = 0; i < obj.m_length; i++)
    {
        m_pointer[i] = obj.m_pointer[i];
    }
}

//数组排序
void DoubArray::sort(const DoubArray& obj)
{
    int len = obj.m_length;

    for(int i = 0; i < len; i++)
    {
        for(int j = 0; j < len - i; j++)
        {
            if( obj.m_pointer[j] < obj.m_pointer[j+1] )
            {
                double temp = obj.m_pointer[j];
                obj.m_pointer[j] = obj.m_pointer[j+1];
                obj.m_pointer[j+1] = temp;
            }
        }
    }
}

//获取数组长度
int DoubArray::length()
{
    return m_length;
}

//获取数组成员
bool DoubArray::get(int index, double& value)
{
    bool ret = (0 <= index) && (index < length());
    if( ret )
    {
        value = m_pointer[index];
    }

    return ret;
}

//设置数组成员
bool DoubArray::set(int index, double value)
{
    bool ret = (0 <= index) && (index < length());
    if( ret )
    {
        m_pointer[index] = value;
    }

    return ret;
}

//遍历数组
void DoubArray::show(const DoubArray& obj)
{
    int len = obj.m_length;
    for(int i = 0; i  < len ; i++)
    {
        cout << obj.m_pointer[i] << endl;
    }
}

//析构函数,销毁数组
DoubArray::~DoubArray()
{
    delete[]m_pointer;
}

主函数调用

cpp 复制代码
#include <iostream>
#include "Array.h"
using namespace std;

int main()
{
    double score = 0;
    int num = 0;
    cout << "请输入学生人数:";
    cin >> num;
    DoubArray stu_a(num);

    for(int i = 0; i < num; i++)
    {

        cout << "请输入第" << i+1 << "个学生的成绩:";
        cin >> score;
        stu_a.set(i, score);
    }

    cout << "学生成绩降序排列如下:";
    stu_a.sort(stu_a);
    stu_a.show(stu_a);

    return 0;
}

程序效果

相关推荐
合作小小程序员小小店18 分钟前
桌面安全开发,桌面二进制%恶意行为拦截查杀%系统安全开发3.0,基于c/c++语言,mfc,win32,ring3,dll,hook,inject,无数据库
c语言·开发语言·c++·安全·系统安全
Codeking__20 分钟前
C++ 11 atomic 原子性操作
开发语言·c++
crescent_悦23 分钟前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
卡提西亚1 小时前
C++笔记-34-map/multimap容器
开发语言·c++·笔记
2***B4491 小时前
C++在金融中的QuantLibXL
开发语言·c++·金融
A***07172 小时前
C++在游戏中的阴影渲染
开发语言·c++·游戏
Q***l6873 小时前
C++在计算机图形学中的渲染
开发语言·c++
oioihoii3 小时前
C++语言演进之路:从“C with Classes”到现代编程基石
java·c语言·c++
咔咔咔的3 小时前
3190. 使所有元素都可以被 3 整除的最少操作数
c++
T***16074 小时前
C++在游戏开发中的AI行为树
开发语言·c++