桂 林 理 工 大 学
实 验 报 告
实验名称 C++程序的结构 日期 2019年 04 月21 日
一、实验目的:
1. 观察程序运行中变量的作用域、生存期和可见性。
2. 学习类的静态成员的使用。
3. 学习多文件结构在C++程序中的使用。
二、实验环境:
Visual C++
三、实验内容:
(写出主要的内容)
1.1. 输入、编译、运行程序lab5_1.cpp,观察变量x、y的值。
#include<iostream>
using namespace std;
void fun1()
{
int x=80,y=90;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}
int x=1,y=2;
int main()
{
cout<<"Begin!"<<endl;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
cout << "Evaluate x and y in main()..." << endl;
int x=20,y=30;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
cout << "Step into fn1()..." << endl;
fun1();
cout<<"Back in main"<<endl;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
return 0;
}
输出结果:Begin!
x=1
y=2
Evaluate x and y in main()…
x=20
y=30
Step into fn1()…
x=80
y=90
Back in main
x=20
y=30
2. 改写实验四中的Point类。在Point.h中定义类的属性及成员函数申明; 在Point.cpp中定义类的成员函数实现;在lab5_2.cpp中测试这个类。注意多文件结构的编译、编辑方法、头文件的包含关系,观察相应的成员变量取值的变化情况。
//Point.h
class Point
{
private:
int X,Y;
public:
Point(int xx=0,int yy=0);
Point(Point &p);
int GetX(){ return X;}
int GetY(){ return Y;}
};
//Point.cpp
#include "Point.h"
#include <iostream.h>
Point::Point(int xx,int yy)
{
X=xx;
Y=yy;
}
Point::Point(Point &p)
{
X=p.X;
Y=p.Y;
cout<<"拷贝构造函数被调用"<<endl;
}
//lab5_2.cpp
#include "Point.h"
#include <iostream.h>
void main(void)
{
Point A(4,5);
Point B(A);
cout<<A.GetX()<<endl;
cout<<B.GetX()<<endl;
}
四、心得体会:
1、理解了程序运行中变量的作用域、生存期和可见性的不同。
2、理解了类中的静态成员函数的使用。
3、通过观察程序的输出,加深了对全局变量、局部变量的作用域、生存期的理解。
4、了解了多文件结构在C++程序中的使用。