歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++對象數組的實例學習

C++對象數組的實例學習

日期:2017/3/1 9:43:39   编辑:Linux編程

C++作為一種面向對象的語言,其面向對象的思維,我覺得非常重要,一直都在研究匯編和C語言,沒有對象的觀念,但是C++裡面,對象思維,抽象思維其實是很有意思的,而且很有意義。

今天,我們來分析學習對象數組,對象數組從名字上分析,就是存放對象的數組,可能對於初學者來說,這是一個新詞,但是對象數組很有用。

我們假設,學生是對象,對象的屬性有ID和Score,那麼如果班級裡面有100個學生,那麼每個對象都要用類進行實例化的話,那真是太恐怖了,此時,C++的對象數組就該上場了,一個數組直接搞定是不是很方便呢?

唯一要注意的事情是:

要創建對象數組,必須要有默認構造函數,但是如果我們聲明了一個構造函數,默認構造函數系統不會給,所以,我們得顯式給出默認構造函數!!

C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm

讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm

讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm

讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm

C++11 獲取系統時間庫函數 time since epoch http://www.linuxidc.com/Linux/2014-03/97446.htm

C++11中正則表達式測試 http://www.linuxidc.com/Linux/2012-08/69086.htm

--------------------我是分割線,下面用代碼說明-----------------

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

}


--------------------我是分割線-------------------------------------------

效果圖:

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

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

加油!!

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

Copyright © Linux教程網 All Rights Reserved