C++程序的多文件组成
生活随笔
收集整理的這篇文章主要介紹了
C++程序的多文件组成
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++程序的多文件組成
【例3.32】 一個源程序按照結構劃分為3個文件
// 文件1 student.h (類的聲明部分) #include<iostream.h> #include<string.h> class Student { private:char *name; // 學生姓名char *stu_no; // 學生學號float score; // 學生成績 public: // 類的外部接口Student(char *name1,char *stu_no1,float score1); // 構造函數~Student(); // 析構函數void modify(float score1); // 數據修改void show(); // 數據輸出 }; // 文件2 student.cpp (類的實現部分) #include "student.h" // 包含類的聲明文件 Student∷Student(char *name1,char *stu_no1,float score1) {name=new char[strlen(name1)+1];strcpy(name,name1);stu_no=new char[strlen(stu_no1)+1];strcpy(stu_no,stu_no1);score=score1; } Student∷~Student() {delete []name;delete []stu_no; } void Student∷modify(float score1) { score=score1; } void Student∷show() {cout<<"\n name: "<<name;cout<<"\n stu_no: "<<stu_no;cout<<"\n score: "<<score; } // 文件3 studentmain.cpp (類的使用部分) #include "student.h" // 包含類的聲明文件 void main() {Student stu1("Liming","990201",90);stu1.show();stu1.modify(88);stu1.show(); }【例3.33】 利用類表示一個堆棧(stack),并為此堆棧建立push()、 pop()及顯示堆棧內容的showstack()等函數
//文件1 stack.h #include <iostream.h> #include <iomanip.h> #include <ctype.h> const int SIZE=10; class stack{int stck[SIZE]; // 數組,用于存放棧中數據int tos; // 棧頂位置(數組下標) public:stack();void push(int ch); // 將數據ch壓入棧int pop(); // 將棧頂數據彈出棧void ShowStack(); }; // 文件2 stack.cpp #include <iostream.h> #include "stack.h" stack∷stack() // 構造函數,初始化棧 { tos= 0; } void stack∷push(int ch) {if(tos==SIZE){cout<<"Stack is full";return;}stck[tos]=ch;tos++;cout<<"You have pushed a data into the stack!\n"; } int stack∷pop() {if (tos==0){cout<<"Stack is empty";return 0;}tos--;return stck[tos]; } void stack∷ShowStack() {cout<<"\n The content of stack: \n" ;if (tos==0){cout<<"\nThe stack has no data!\n";return;}for (int i=tos-1; i>=0;i--)cout<<stck[i]<<" ";cout<<"\n\n"; } //文件3 stackmain.cpp #include <iostream.h> #include "stack.h" main() {cout<<endl;stack ss;int x;char ch;cout<<" <I> ------ Push data to stack\n";cout<<" <O> ------ Pop data from stack\n";cout<<" <S> ------ Show the content of stack\n";cout<<" <Q> ------ Quit... \n";while (1){cout<<"Please select an item: ";cin>>ch;ch=toupper(ch);switch(ch){case 'I':cout<<"\n Enter the value that "<<"you want to push: ";cin >>x;ss.push(x);break;case 'O':x=ss.pop();cout<<"\n Pop "<<x<<" from stack.\n"; break;case 'S':ss.ShowStack();break;case 'Q':return 0;default:cout<<"\n You have inputted a wrong item! Please try again!\n";continue;}} }轉載于:https://www.cnblogs.com/whale90830/p/10542444.html
總結
以上是生活随笔為你收集整理的C++程序的多文件组成的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小动物超声成像系统进口与国产的区别
- 下一篇: 汽油进1000方罐多少压力是安全的有没有