c++:一個程式多個源/標頭檔案
阿新 • • 發佈:2019-01-26
1、一個程式,一個原始檔的做法
#include<iostream> #include<cstring> using namespace std; class Student { private: char Name[20]; //學生姓名 double Chinese; //語文成績 double Math; //數學成績 public: double Average( );//計算平均成績 double Sum( ); //計算總分 void Show( ); //列印資訊 void SetStudentdent(char*,double,double);//為物件置姓名、成績 void SetName(char *); //為物件置姓名 char *GetName( ); //取得學生姓名 }; double Student::Average( ) { return (Chinese+Math)/2; }//平均成績 double Student::Sum( ) { return Chinese+Math; } //總分 void Student::Show( ) //列印資訊 { cout<<"Name: "<<Name<<endl<<"Score: "<<Chinese<<'\t'<< Math<<'\t'<<"average: "<<Average()<<'\t'<<"Sum: "<<Sum()<<endl; } void Student::SetStudentdent(char *name,double chinese,double math) { strcpy(Name,name); //置姓名 Chinese=chinese; //置語文成績 Math=math; //置數學成績 } void Student::SetName(char *name) { strcpy(Name,name); //置姓名 } char * Student::GetName( ) { return Name; }//返回姓名 int main( ) { Student p1,p2; p1.SetStudentdent("Li qing",98,96); //物件置初值 p2.SetStudentdent("Wang Gang",90,88); //物件置初值 p1.Show();//列印資訊 p2.Show();//列印資訊 p1.SetName("Zhao jian");//重新置p1物件的名字 p1.Show(); cout<<"p1.Name: "<<p1.GetName()<<endl;//列印物件的名字 cout<<"p1.average: "<<p1.Average()<<endl;//列印物件的成績 return 0; }
2、一個程式,多個源/標頭檔案的做法
student.h
#ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED class Student { private: char Name[20]; //學生姓名 double Chinese; //語文成績 double Math; //數學成績 public: double Average( );//計算平均成績 double Sum( ); //計算總分 void Show( ); //列印資訊 void SetStudentdent(char*,double,double);//為物件置姓名、成績 void SetName(char *); //為物件置姓名 char *GetName( ); //取得學生姓名 }; #endif // STUDENT_H_INCLUDED
student.cpp
#include<iostream> #include<cstring> #include "student.h" //預處理程式碼,相當於將student.h原模原樣copy過來了 using namespace std; double Student::Average( ) { return (Chinese+Math)/2; }//平均成績 double Student::Sum( ) { return Chinese+Math; } //總分 void Student::Show( ) //列印資訊 { cout<<"Name: "<<Name<<endl<<"Score: "<<Chinese<<'\t'<< Math<<'\t'<<"average: "<<Average()<<'\t'<<"Sum: "<<Sum()<<endl; } void Student::SetStudentdent(char *name,double chinese,double math) { strcpy(Name,name); //置姓名 Chinese=chinese; //置語文成績 Math=math; //置數學成績 } void Student::SetName(char *name) { strcpy(Name,name); //置姓名 } char * Student::GetName( ) { return Name; }//返回姓名
main.cpp
#include<iostream>
#include "student.h" //預處理程式碼,相當於將student.h原模原樣copy過來了
using namespace std;
int main( )
{
Student p1,p2;
p1.SetStudentdent("Li qing",98,96); //物件置初值
p2.SetStudentdent("Wang Gang",90,88); //物件置初值
p1.Show();//列印資訊
p2.Show();//列印資訊
p1.SetName("Zhao jian");//重新置p1物件的名字
p1.Show();
cout<<"p1.Name: "<<p1.GetName()<<endl;//列印物件的名字
cout<<"p1.average: "<<p1.Average()<<endl;//列印物件的成績
return 0;
}
何時用標頭檔案.h:
在標頭檔案中,劃橫線的程式碼部分主要防止其class函式體部分被在其他檔案重複#include的時候重複定義發生錯誤,所以如果已經被定義過的class就不再被定義了!
類庫:
一個類宣告放在一個頭檔案中,所有的標頭檔案形成一個類庫;