今天繼續完成上周沒有完成的習題---C++第三章課后作業,本章題涉及指針的使用,有指向對象的指針做函數參數,對象的引用以及友元類的使用方法等
它們具體的使用方法在下面的題目中會有具體的解析(解析標注在代碼中)。
題目:
1.建立一個對象數組,內放5個學生數據(學號,成績),設立一個函數max,用指向對象的指針作函數參數,在max函數中找出5個學生中成績最高者,並輸出其學號。
1 #include <iostream> 2 #include<stdlib.h> 3 using namespace std; 4 class Student 5 {public: 6 //定義學生數據函數 7 Student(int n,float s):num(n),score(s){} 8 int num; 9 float score; 10 }; 11 12 void main() 13 { 14 //構建五個學生數據信息 15 Student stud[5]={ 16 Student(101,78.5),Student(102,85.5),Student(103,98.5), 17 Student(104,100.0),Student(105,95.5)}; 18 void max(Student* );//定義max函數 19 Student *p=&stud[0];//p指向數組第一個元素,p為實參,arr為形參 20 max(p);//調用函數,找到學生中成績最高者,並輸出其學號 21 } 22 //構建max函數,用指向對象(學生)的指針作函數的參數 23 void max(Student *arr) 24 { //假設學號為1的學生成績最高 25 float max_score=arr[0].score; 26 int k=0; 27 //通過循環,逐個比較學生的成績,直到查詢完所有學生成績,並返回最大值 28 for(int i=1;i<5;i++) 29 { 30 if(arr[i].score>max_score) 31 { 32 max_score=arr[i].score; 33 k=i; 34 } 35 } 36 //打印出成績最大的學生的學號和成績 37 cout<<arr[k].num<<" "<<max_score<<endl; 38 system("pause"); 39 }
2.修改第6題的程序,增加一個fun函數,改寫main函數。改為在fun函數中調用change和display函數。在fun函數中使用對象的引用(Student &)作為形參。
1 #include<iostream> 2 #include<stdlib.h> 3 using namespace std; 4 class Student 5 { 6 public: 7 //學生數據的構造函數 8 Student(int n,float s):num(n),score(s){} 9 //修改學生成績的函數 10 void change(int n,float s){num = n;score = s;} 11 //輸出學生成績和學號的函數 12 void display(){cout<<num<<" "<<score<<endl;} 13 private: 14 int num; 15 float score; 16 }; 17 //在fun函數中使用對象的引用(Student & stud)作為形參 18 void fun (Student & stud){ 19 cout<<"修改前的學生數據信息"<<endl; 20 stud.display(); 21 //調用change函數進行對學生數據信息的修改 22 stud.change(101, 80.5); 23 cout<<"修改后的學生數據信息"<<endl; 24 stud.display(); 25 } 26 int main() 27 { 28 //定義一個學生數據信息 29 Student stud(101, 78.5); 30 //調用fun函數 31 fun(stud); 32 system("pause"); 33 return 0; 34 35 36 }
3.將例3.13中的Time類聲明為Date類的友元類,通過Time類中的display函數引用Date類對象的私有數據,輸出年,月,日和時,分,秒。
1 #include <iostream> 2 #include<stdlib.h> 3 using namespace std; 4 //聲明Time,因為在Date中提前使用 5 class Time; 6 class Date{ 7 public: 8 Date(int,int,int); 9 //將Time類聲明為Date類的友元類 10 friend Time; 11 private: 12 int month; 13 int day; 14 int year; 15 }; 16 //Date函數 17 Date::Date(int y,int m,int d):year(y),month(m),day(d){ } 18 class Time{ 19 public: 20 Time(int,int,int); 21 void display(const Date &); 22 private: 23 int hour; 24 int minute; 25 int sec; 26 }; 27 //Time函數 28 Time::Time(int h,int m,int s):hour(h),minute(m),sec(s){ } 29 //display函數 30 void Time::display(const Date &d){ 31 //引用Date類中的私有數據 32 cout<<d.year<<"/"<<d.month<<"/"<<d.day<<endl; 33 //引用本類中的私有數據 34 cout<<hour<<":"<<minute<<":"<<sec<<endl;} 35 int main(){ 36 Time t1(17,15,50); 37 Date d1(2019,10,28); 38 //通過Time類中的display函數引用Date類對象的私有數據 39 t1.display(d1); 40 system("pause"); 41 return 0; 42 }
小結:
指針在編程學習過程中,是非常復雜的,必須非常明了其中的邏輯指向,才能更好的運用指針解決問題。C語言的指針使用非常廣泛,但C++涉及的指針內容不多,主要為指針指向數組指定元素,指針指向函數,用指向對象的指針做函數參數幾種。明確指針的指向和指針的取值,指針部分的學習就不難了。