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;
}

程序效果

相关推荐
岁忧12 分钟前
(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
java·c++·leetcode·游戏·go·深度优先
小欣加油12 分钟前
leetcode 3 无重复字符的最长子串
c++·算法·leetcode
zylyehuo3 小时前
C++基础编程
c++
tt5555555555554 小时前
C/C++嵌入式笔试核心考点精解
c语言·开发语言·c++
lg_cool_4 小时前
Qt 中最经典、最常用的多线程通信场景
c++·qt6.3
科大饭桶4 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
tt5555555555555 小时前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵
rainFFrain6 小时前
Boost搜索引擎项目(详细思路版)
网络·c++·http·搜索引擎
long_run6 小时前
C++之模板函数
c++
NuyoahC6 小时前
笔试——Day43
c++·算法·笔试