C++对象数组的实例学习


C++作为一种面向对象的语言,其面向对象的思维,我觉得非常重要,一直都在研究汇编和C语言,没有对象的观念,但是C++里面,对象思维,抽象思维其实是很有意思的,而且很有意义。

今天,我们来分析学习对象数组,对象数组从名字上分析,就是存放对象的数组,可能对于初学者来说,这是一个新词,但是对象数组很有用。

我们假设,学生是对象,对象的属性有ID和Score,那么如果班级里面有100个学生,那么每个对象都要用类进行实例化的话,那真是太恐怖了,此时,C++的对象数组就该上场了,一个数组直接搞定是不是很方便呢?

唯一要注意的事情是:

要创建对象数组,必须要有默认构造函数,但是如果我们声明了一个构造函数,默认构造函数系统不会给,所以,我们得显式给出默认构造函数!!

C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码

读C++ Primer 之构造函数陷阱

读C++ Primer 之智能指针

读C++ Primer 之句柄类

C++11 获取系统时间库函数 time since epoch

C++11中正则表达式测试

--------------------我是分割线,下面用代码说明-----------------

# include <iostream>

# include <string>

using namespace std;

 

const int Objarr_Number = 5;

 

class Student

{

public:

    Student(string, int);//构造函数

    Student();          //默认构造函数一定要有 

    void Print();        //声明输出函数

    string ID;

    int score;

};

 

Student::Student(string s, int n)

{

    ID = s;

    score = n;

}

 

void Student::Print()

{

    cout << "ID :  "<< ID  << "  " << "Score: "<< score << endl;

}

 

int main(void)

{

    Student stud[Objarr_Number] = {

        Student("001", 90),

        Student("002", 94),

        Student("003", 70),

        Student("004", 100),

        Student("005", 60),

    };

 

    int max = stud[0].score;

    int i = 0;

    int k = 0; 

 

    cout << "ID " << "\t" << "Score  "<< endl;

    for(i = 0; i< Objarr_Number; i++)

    {

        //输出对象数组的值

        cout << stud[i].ID <<"\t" << stud[i].score << endl;

        //以成绩来进行比较

        if(stud[i].score > max)

        {

            k = i;

            max = stud[i].score;

        }

    }

 

    cout <<"-----------------------------"<<endl;

    cout << "The Max Score is  " ;

    //输出最大的学生的成绩

    stud[k].Print();

 

    cout << endl;

    return 0;

}


--------------------我是分割线-------------------------------------------

效果图:

C++对象数组的实例学习

----------------------------------------------------------------------------------------------

手工敲一遍,理解更深刻!!!

加油!!

----------------------------------------------------------------------------------------------

本文永久更新链接地址:

相关内容