第一篇:C++上機實驗:名稱空間和頭文件
實驗6 名稱空間和頭文件
1.實驗目的
學習并理解變量的作用域;掌握頭文件的使用方法;掌握名稱空間的作用和使用方法。
2.實驗要求
(1)掌握全局變量和靜態變量的作用域。
(2)掌握頭文件的使用方法。
(3)掌握名稱空間的使用方法。
3.實驗內容
(1)全局變量一般在函數的外部定義,運行下面程序并思考變量的作用域。
#include
int a=3;//全局變量
int main(){
int a=5;cout< (2)靜態變量(static).靜態變量之所以是因為靜態,是因為他在整個程序生命周期的地址靜止不變。也就是說在整個程序里面只保存有一份拷貝。運行下面兩個程序并思考靜態變量的規則。 #include int max_so_far(int curr)//求至今(本次調用)為止最大值 { static int biggest=0;//該變量保持著每次調用時的最新值,它的有效期等于整個程序的有效期,如果去掉static,同學們看看程序運行的結果是什么? cout< if(curr > biggest) biggest = curr; return biggest;} int main() { cout< return 0; } #include void fun1() { static int value = 1;//體會靜態變量的作用:函數調用結束后,其所占用的地址依然存在 value=value+1; cout< } int main() { fun1(); fun1(); fun1(); return 0; } (3)為了實現協同開發,減少開發時間,降低錯誤,提高效率,C++提供了頭文件和名稱空間機制。一般函數、全局變量、類、名稱等的聲明放在擴展名為.h(稱為接口interface文件)的頭文件中,而其實現部分則放在相同主名,擴展名為.cpp(稱為實現implementation文件),而用戶的應用程序則是調用(稱為應用application文件) //E:cfun.h 頭文件的定義 #ifndef FUN_H #define FUN_H #include //E:cfun.cpp 實現部分的定義 #include int f(int x){ } #include //E:ccpp1.cpp 應用程序的定義 int main(){ } cout< (4)名稱空間主要是為了解決重名的問題 #ifndef FUN_H #define FUN_H #include namespace n1{ namespace n2{ #endif #include //extern int n1::a=1;//extern int n2::a=2;int f(int);} int f(int);} int n1::f(int x){ } int n2::f(int x){ } #include } cout< (1)利用頭文件的方式,寫出實現數學運算(+,-,*,/,%,^)的函數庫(mathsx),然后在主程序中調用,體會頭文件的作用 (2)利用名稱空間的方法,分別在兩個名稱空間中實現交換兩個變量的值的函數,分別用指針和引用作為參數swap(int *, int *)以及swap(int & ,int &)然后在主程序中調用,體會函數的闡述傳遞的規則 第二次上機實驗報告 姓名:王小寧 班級: 學號: 031012 1234 第一題: 題目: 編寫一個類,聲明一個數據成員和一個靜態數據成員,其構造函數初始化數據成員,并把靜態數據成員加1,其析構函數把靜態數據成員減1.(1)編寫一個應用程序,創建該類的3個對象,然后顯示其數據成員和靜態數據成員,再析構每個對象,并顯示它們對靜態數據成員的影響。 (2)修改該類,增加靜態成員函數并訪問靜態數據成員,并聲明靜態數據成員為保護成員。體會靜態成員函數的使用,靜態成員之間與非靜態成員之間互訪問題。 編程思想: 首先,定義一個類,其中含有兩個類的私有變量,一個靜態數據變量,定義構造函數,將初值賦給兩個私有變量,并將靜態數據變量加1,并顯示.定義一個析構函數,并通過析構函數將靜態成員變量減1.并顯示。 修改以上的類,增加一個靜態成員函數并通過靜態成員函數來訪問靜態成員變量。在主函數中利用一個指向函數的指針指向這個靜態成員函數,并通過這個指針來訪問類中的靜態數據。代碼實現: 代碼1: #include static int count; A(int a=0,int b=0) { X=a; Y=b; count++; cout<<“startcount=”< count--; cout<<“overcount=”< int GetX(){return X;} int GetY(){return Y;} private: int X,Y;};int A::count=0;int main(){ int *countp=&A::count;A z(2,3);cout<<“x=”< cout<<“x=”< 問題及心得: 在這次試驗中,我理解了靜態變量與普通變量之間的差異與聯系。在實驗過程中因未初靜態變量始化而無法通過編譯,并且注意到靜態變量一定要在類外初始化。 題目2: 創建一個Person類,該類中有字符數組,表示姓名、街道地址、市、省和郵政編碼。其功能有修改姓名、顯示數據信息。要求其功能函數的原型放在類定義中,構造函數初始化每個成員,顯示信息函數要求把對象中的完整信息打印出來。其中數據成員為保護的,函數為公有的。 編程思想: 創建一個PERSON類,定義姓名、街道地址、市、省和郵政編碼分別為CHAR型的指針私有型變量。在定義公有型的構造函數,并在構造函數中申請動態內存來保存初始化的內容,并用相應的私有性的指針變量指向,再利用復制函數則指針中將會存放入輸入內容。定義公有的析構函數釋放動態申請的空間。定義一個公有的改變函數改變其中一個變量,方法與構造函數相似。 代碼實現: #include private: char *name;char *street;char *pro;char *city;char *code; public: Person(char *aname,char *astreet,char *apro,char *acity,char *acode){ name=new char[strlen(aname)+1]; strcpy(name,aname); street=new char[strlen(astreet)+1]; strcpy(street,astreet); pro=new char[strlen(apro)+1]; strcpy(pro,apro); city=new char[strlen(acity)+1]; strcpy(city,acity); code=new char[strlen(acode)+1]; strcpy(code,acode); cout<<“constructor”< delete[] name; delete[] street; delete[] pro; delete[] city; delete[] code; cout<<“destructor”< delete[] name; name=new char[strlen(aname)+1]; strcpy(name,aname);} void show(){ cout<<“姓名:”< cout<<“街道地址:”< cout<<“省份:”< cout<<“城市:”< cout<<“郵政編碼:”< 運行結果: 實驗心得: 通過這個實驗,我們學會了對類的私有的字符數組變量的初始化。利用指針動態分配空間。 C++上機實驗報告 實驗名稱:實驗 專業班級: 姓 名: 學 號: 實驗日期: 11 實驗 目錄 1.實驗目的 2.實驗內容 3.程序代碼 4.調試結果 5.實驗心得 1.實驗目的 實驗10(1)進一步了解運算符重載的概念和使用方法;(2)掌握幾種常用的運算符重載的方法;(3)了解轉換構造函數的使用方法; (4)了解在Visual C++6.0環境下進行運算符重載要注意的問題。實驗11(1)了解繼承在面向對象程序設計中的重要作用;(2)進一步理解繼承和派生的概念; (3)掌握通過繼承派生出一個新的類的方法;(4)了解虛基類的作用和用法。 2.實驗內容 實驗10 事先編好程序,上機進行調試和運行程序,分析結果。(1)聲明一個復數類Complex,重載運算符“+”,“-”,“*”,“/”,使之能用于復數的加,減,乘,除,運算符重載函數作為Complex類成員的函數。編程序,分別求兩個復數之和,差,積和商。(2)聲明一個復數類Complex,重載運算符“+”,使之能用于復數的加法運算。參加運算的兩個運算量可以都是類對象,也可以其中有一個是整數,順序任意。 運行程序,分別求兩個復數之和,整數和復數之和,(3)有兩個矩陣a和b,均為2行3列。求兩個矩陣之和。重載運算符“+”,使之能用于兩個矩陣相加 (4)聲明一個Teacher(教師)類和一個Student(學生)類,二者有一部分數據成員是相同的,例如num(號碼),name(名字),sex(性別)。編寫程序,將一個Student對象(學生)轉換為Teacher(教師)類,只將以上三個相同的數據成員移植過去??梢栽O想為:一位學生大學畢業了,留校擔任教師,他原有的部分數據對現在的教師身份來說任然是有用的,應當保留并成為其教師的數據的一部分。 實驗11 事先編寫好程序,上機調試和運行程序,分析結果。 (1)將教材第11章例11.1的程序片段補充和改寫成一個完整的、正確的程序,用公用繼承方式。在程序中應當包括輸入數據的函數,在程序運行時輸入num,name,sex,age,addr的值,程序應輸出以上5個數據的值。 (2)將教材第11章例11.3的程序修改、補充,寫成一個完整、正確的程序,用保護繼承方式。在程序中應包括輸入數據的函數。(3)修改上面第(2)題的程序,改為用公用繼承方式。上機調試程序,使之能夠正確運行并得到正確的結果。 對這兩種繼承方式做比較分析,考慮在什么情況下二者不能互相替換。 (4)分別聲明Teacher(教師)類和Cadre(干部)類,采用多 重繼承方式由這兩個類派生出新類Teacher-Cadre(教師兼干部)。要求: Ⅰ.在兩個基類中都包含姓名、年齡、性別、地址、電話等數據成員。 Ⅱ.在Teacher類中還包含數據成員title(職稱),在Cadre類中還包含數據成員post(職務)。在Teacher-Cadre類中還包含數據成員wages(工資)。 Ⅲ.在基類中的姓名、年齡、性別、地址、電話等數據成員用相同的名字,在引用這些數據成員時,指定作用域。Ⅴ.在類體中聲明成員函數,在類外定義成員函數。 Ⅵ.在派生類Teacher-Cadre的成員函數show中調用Teacher類中的display函數,輸出性命、年齡、性別、職稱、地址、電話,然后再用cout語句輸出職務與工資。 3.程序代碼 實驗10(1) #include Complex Complex::operator +(Complex &c2){Complex c;c.real=real+c2.real;c.imag=imag+c2.imag;return c;} Complex Complex::operator-(Complex &c2){Complex c;c.real=real-c2.real;c.imag=imag-c2.imag;return c;} Complex Complex::operator*(Complex &c2){Complex c;c.real=real*c2.real-imag*c2.imag;c.imag=imag*c2.real+real*c2.imag;return c;} Complex Complex::operator/(Complex &c2){Complex c;c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);return c;} void Complex::display(){cout<<“(”< (2) #include double real; double imag;}; Complex Complex::operator+(Complex &c){return Complex(real+c.real,imag+c.imag);} Complex Complex::operator+(int &i){return Complex(real+i,imag);} void Complex::display(){cout<<“(”< Complex operator+(int &i,Complex &c){return Complex(i+c.real,c.imag);} int main(){Complex c1(3,4),c2(5,-10),c3;int i=5;c3=c1+c2;cout<<“c1+c2=”;c3.display();c3=i+c1;cout<<“i+c1=”;c3.display();c3=c1+i;cout<<“c1+i=”;c3.display();return 0;}(3) #include int mat[2][3];}; Matrix::Matrix(){for(int i=0;i<2;i++)for(int j=0;j<3;j++)mat[i][j]=0;} Matrix operator+(Matrix &a,Matrix &b){Matrix c;for(int i=0;i<2;i++)for(int j=0;j<3;j++){c.mat[i][j]=a.mat[i][j]+b.mat[i][j];} return c;} void Matrix::input(){cout<<“input value of matrix:”< void Matrix::display(){for(int i=0;i<2;i++){for(int j=0;j<3;j++){cout< #include int num; char name[20]; char sex; float score;}; Student::Student(int n,char nam[],char s,float sco){num=n;strcpy(name,nam);sex=s;score=sco;} class Teacher {public: Teacher(){} Teacher(Student&);Teacher(int n,char nam[],char sex,float pay);void display();private: int num; char name[20]; char sex; float pay;}; Teacher::Teacher(int n,char nam[],char s,float p} {num=n;strcpy(name,nam);sex=s;pay=p;} Teaxher::Teacher(Student& stud){num=stud.get_num();strcpy(name,stud.get_name());sex=stud.get.sex();pay=1500;} void Teacher::display(){cout<<“num:”< #include void get_value() {cin>>num>>name>>sex;} void display() {cout<<”num:“< cout<<”sex:“< int num; char name[10];char sex;}; class Student1:public Student {public: void get_value_1(){get_value();cin>>age>>addr;} void display_1(){cout<<”age:“< char addr[30];}; int main(){Student1 stud1;stud1.get_value_1();stud1.display();stud1.display_1();return 0;}(2) #include void display();protected: int num; char name[10]; char sex;}; void Student::get_value(){cin>>num>>name>>sex;} void Student::display(){cout<<”num:“< class Student1:protected Student {public: void get_value_1();void display1();private: int age;char addr[30];}; void Student1::get_value_1(){get_value();cin>>age>>addr;} void Student1::display1(){cout<<”num:“< int main(){Student1 stud1;stud1.get_value_1();stud1.display1();return 0;}(3) #include int num; char name[10]; char sex;}; void Student::get_value(){cin>>num>>name>>sex;} void Student::display(){cout<<”num:“< class Student1:public Student {public: void get_value_1();void display1();private: int age; char addr[30];}; void Student1::get_value_1(){get_value();cin>>age>>addr;} void Student1::display1(){cout<<”num:“< int main(){Student1 stud1;stud1.get_value_1();stud1.display1();return 0;}(4) #include Teacher(int,char[],char);void display();private: int num;char name[20];char sex;}; Teacher::Teacher(int n,char nam[],char s){num=n;strcpy(name,nam);sex=s;} void Teacher::display(){cout<<”num:”< class BirthDate {public: BirthDate(int,int,int);void display();void change(int,int,int);private: int year;int month;int day;}; BirthDate::BirthDate(int y,int m,int d){year=y;month=m;day=d;} Void BithDate::display(){cout<<”birthday:”< void BirthDate::change(int y,int m,int d){year=y;month=m;day=d;} class Professor:public Teacher {public: Professor(int,char[],char,int,int,int,float);void display();void change(int,int,int);private: float area;BirthDate birthday;} Professor::Professor(int n,char name[20],char s,int y,int m,int d,float a): Teacher(n,name,s),birthday(y,m,d),area(a){} void Professor::display(){Teacher::display();birthday.display();cout<<”area:”< Int main(){Professor profl(3012,”Zhang”,’f’,1949,10,1,125.4);cout< 4.調試結果 實驗10(1)c1+c2=(8,-6i)c1-c2=(-2,14i)c1*c2=(55,-10i)c1/c2=(-0.2,0.4)(2)c1+c2=(8,-6i)i+c1=(8,4i)c1+i=(8,4i) (3) input value of Matrix:11 22 33 44 55 66 input value of Matrix:12 13 14 15 16 17 Matrix a: 11 22 33 44 55 66 Matrix b: 12 13 14 15 16 17 Matrix c=Matrix a + Matrix b : 23 25 47 59 71 83 (4)student1 : num :20010 name:Wang sex:m score;89.5 Teacher2: num:20010 name:Wang sex:m pay:1500 實驗11(1) 10101 Li M 20 Beijing num:10101 name:Li sex:M age:20 address:Beijing (2) 10101 Li M 20 Beijing num:10101 name:Li sex:M age:20 address:Beijing (3) 10101 Li M 20 Beijing num:10101 name:Li sex:M age:20 address:Beijing (4)The original data: num:3012 name:Zhang sex:f area:125.4 The new data: num:3012 name:Zhang sex:f birthday:6/1/1950 area:125.4 5.實驗心得 這一次上機實驗,除了了解到了運算符重載的概念和用法,掌握幾種常用的運算符重載的方法,了解轉換構造函數的使用方法,同時也能了解虛基類的用法,理解繼承與派生的概念。 但是,最主要的,我覺得,是通過這一次的上機實驗,我了解到,有的實驗本身是沒有程序錯誤的,但是,也會由于實驗環境的影響而不能正常運行。換句話說,有的程序并不能在Visaul C++的環境下運行,而不是程序自身的問題。所以,對于沒辦法調試成功的程序,我們也不能一味的認為程序有錯誤,要學會理性的判斷程序的對錯,再下結論。 C++課程上機實驗常見錯誤匯集 1. 調試器錯誤信息:syntax error : missing ';' 原因:在源碼中遺失“;” 2.調試器錯誤信息:例:error C2065: 'cout' : undeclared identifier.原因:例如cout/cin/endl/<>>等在命名空間中定義的符號和標示符無法使用。缺少命名空間使用定義:即缺少“using namespace std;” 3. 調試器錯誤信息:例:error C2065: 'i' : undeclared identifier原因:變量未定義就直接使用.C++語言中,變量的使用必需遵循先聲明定義,后使用的原則。 4.調試器錯誤信息:error C2018: unknown character '0xa3' 原因:在程序中使用中文標示符,如將英文”;”錯誤輸入成了”;”在C++中,除程序注釋可以采用中文外,其余字符要求使用英文。不少同學在建立工程或程序名稱時也使用中文名稱,建議改掉這種習慣。 5.調試器錯誤信息:例:error C2676: binary '>>' : 'class std::basic_ostream 原因:在使用輸入輸出流的時候錯誤使用了標示符“>>”“<<”,例cout>>a; 6.調試器錯誤信息:warning C4305: 'initializing' : truncation from 'const double' to 'float' 原因:定義的變量類型與使用不對應,如聲明為float,但實際給與了一個double的值,例:float pi=3.***; 7.調試器錯誤信息:warning C4700: local variable 'a' used without having been initialized 原因:變量在賦值之前就使用,例:int a, b, c;c=a+b;cin>>a>>b; 8. error C2556: 'int __cdecl main(void)' : overloaded function differs only by return type from 'void __cdecl main(void)' E:tempalskdfldid.cpp(4): see declaration of 'main' E:tempalskdfldid.cpp(15): error C2371: 'main' : redefinition;different basic types 原因:在一個工程中包含多于一個的main函數 9.調試器錯誤信息:error C2447: missing function header(old-style formal list?) 原因:在函數定義的()后面使用分號 例:void chang(); {?..} 10.調試器錯誤信息:error C2660: 'chang' : function does not take 2 parameters 原因:函數聲明/定義/調用參數個數不匹配。 例:void chang(int a,int b, float c) {?} void main() {?chang(3,4);} 11、atal error C1010: unexpected end of file while looking for precompiled header directive。 原因:尋找預編譯頭文件路徑時遇到了不該遇到的文件尾。(一般是沒有#include “stdafx.h”) 12、fatal error C1083: Cannot open include file: 'R??.h': No such file or directory 原因:不能打開包含文件“R??.h”:沒有這樣的文件或目錄。 13、error C2011: 'C??': 'class' type redefinition 原因:類“C??”重定義。 14、error C2018: unknown character '0xa3' 原因:不認識的字符'0xa3'。(一般是漢字或中文標點符號) 15、error C2057: expected constant expression 原因:希望是常量表達式。(一般出現在switch語句的case分支中) 16、error C2065: 'IDD_MYDIALOG' : undeclared identifier 原因:“IDD_MYDIALOG”:未聲明過的標識符。 17、error C2082: redefinition of formal parameter 'bReset' 原因:函數參數“bReset”在函數體中重定義。 18、error C2143: syntax error: missing ':' before '{' 原因:句法錯誤:“{”前缺少“;”。 19、error C2146: syntax error : missing ';' before identifier 'dc' 原因:句法錯誤:在“dc”前丟了“;”。 20、error C2196: case value '69' already used 原因:值69已經用過。(一般出現在switch語句的case分支中) 21、error C2509: 'OnTimer' : member function not declared in 'CHelloView'原因:成員函數“OnTimer”沒有在“CHelloView”中聲明。 22、error C2511: 'reset': overloaded member function 'void(int)' not found in 'B' 原因:重載的函數“void reset(int)”在類“B”中找不到。 23、error C2555: 'B::f1': overriding virtual function differs from 'A::f1' only by return type or calling convention 原因:類B對類A中同名函數f1的重載僅根據返回值或調用約定上的區別。 24、error C2660: 'SetTimer' : function does not take 2 parameters原因:“SetTimer”函數不傳遞2個參數。 25、warning C4035: 'f??': no return value 原因:“f??”的return語句沒有返回值。 26、warning C4553: '= =' : operator has no effect;did you intend '='?原因:沒有效果的運算符“= =”;是否改為“=”? 27、warning C4700: local variable 'bReset' used without having been initialized 原因:局部變量“bReset”沒有初始化就使用。 28、error C4716: 'CMyApp::InitInstance' : must return a value原因:“CMyApp::InitInstance”函數必須返回一個值。 29、LINK : fatal error LNK1168: cannot open Debug/P1.exe for writing 原因:連接錯誤:不能打開P1.exe文件,以改寫內容。(一般是P1.Exe還在運行,未關閉) 30、error LNK2001: unresolved external symbol “public: virtual _ _thiscall C??::~C??(void)” 原因:連接時發現沒有實現的外部符號(變量、函數等)。 上機實驗: 1、回文是指正讀,反讀均相同的字符序列,如“abba”和“abdba”均是回文,但是“good”不是回文,試用STACK類編寫該程序。 #include int top = 1;char *cMyStack =(char *)malloc((iLen/2+1)*sizeof(char));//定位對原始數組的檢測索引初始位置 cMyStack[0] = iLen/2;if(1 == iLen%2){ ++cMyStack[0];} //將原始數組的一半元素入棧 for(top=1;top<=iLen/2;top++){ cMyStack[top] = *(cScr+top-1);} //從棧頂開始依次匹配 while(*(cScr+cMyStack[0])== cMyStack[--top] && cMyStack[0]++ < iLen){} if(0 == top){//是回文數 free(cMyStack);return 1;} else {//不是回文數 free(cMyStack);return 0;} } 運行結果: 2.利用兩個棧類S1、S2模擬一個隊列時,編寫一程序利用棧的運算實現隊列的插入、刪除以及判斷隊列空的運算。 #include template assert(!mStack2.empty());mStack2.pop();} template sq.pushBack(1);printQueue(sq);sq.pushBack(2);printQueue(sq);sq.pushBack(3);printQueue(sq);sq.popFront();printQueue(sq);sq.popFront();printQueue(sq);sq.popFront();printQueue(sq);return 0;} 運行結果: 實驗2: 聲明復數的類Complex,使用友元函數add實現復數的加法。 #include < iostream > using namespace std; class Complex { private: double real, image;public : Complex(){} Complex(double a,double b) { real = a;image = b;} void setRI(double a, double b){ real = a;image = b;} double getReal(){ return real;} double getImage(){ return image;} void print(){ if(image>0) cout<<“復數:”<< real <<“ + ”<< image <<“i”<< endl;if(image<0) cout<<“復數:”<< real <<“-”<< image <<“i”<< endl;} friend Complex add(Complex ,Complex);//聲明友元函數 }; Complex add(Complex c1, Complex c2)//定義友元函數 { Complex c3; c3.real = c1.real + c2.real;//訪問Complex類中的私有成員 c3.image = c1.image + c2.image;return c3;} void main(){ Complex c1(29, 0.634), c2, c3;c2.setRI(85,106.012);c3 = add(c1, c2); cout<<“復數一:”;c1.print();cout<<“復數二:”;c2.print();cout<<“相加后:”;c3.print();} 結果: 實驗三: 7-5 定義一個基類Shape,在此基礎上派生出一個Rectangle和Circle,二者都有getArea()函數計算對象的面積。使用Rectangle類創建一個派生類Square.#include public: Shape(){} double GetArea() { return 0.1;} };class Rectangle: public Shape { public: Rectangle(double w,double h) { width=w;height=h;} double GetArea(){ return width*height;} private: double width,height;};class Circle:public Shape { private: double r; public: Circle(double rr){ r=rr;} double GetArea(){ return PI*r*r;} }; int main(){ Rectangle * rec=new Rectangle(5,6); Circle * cir=new Circle(5); cout<<“RecArea:”< cout<<“CirArea:”< return 1; } 運行結果: 7-10.定義一個Object類,有數據成員weight及相應的操作函數,由此派生出Box類,增加數據成員height和width及相應的操作函數,聲明一個Box對象,觀察構造函數和析構函數的調用順序。#include object(){ cout<<“構造object對象”< class box:public object { private: int Height,Width;public: box(){ cout<<“構造box對象”<第二篇:C++上機實驗報告
第三篇:C++上機實驗報告
第四篇:C++課程上機實驗常見錯誤匯集
第五篇:C++實驗