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