当前位置:文档之家› 第5章上机实验报告

第5章上机实验报告

第5章上机实验报告
一、实验目的
(1)观察程序运行中变量的作用域74。

(2)学习类的静态成员的使用。

(3)学习多文件结构的C++程序中的使用。

二、实验任务
(1)运行下面的程序,观察变量x,y的值。

【代码lab5-1】
#include"iostream"
usingnamespace std;
void fun();
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=10,y=20;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
cout<<"Step into fun()..."<<endl;
fun();
cout<<"Back in main()..."<<endl;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
return 0;
}
void fun()
{
int y=200;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}
//client.h
#ifndef CLIENT_H_INCLUDED
#define CLIENT_H_INCLUDED usingnamespace std;
class Client
{
public:
Client();
Client(Client&p);
~Client();
staticvoid ChangeServerName(string Name); void show();
private:
static string serName;
staticint clientNum;
};
#endif// CLIENT_H_INCLUDED
//client.cpp
#include"iostream"
#include"client.h"
usingnamespace std;
int Client::clientNum=0;
string Client::serName="ser";
Client::Client()
{
clientNum++;
cout<<"第"<<clientNum<<"个客户创建"<<endl; serName=serName;
cout<<"Calling Constructing!"<<endl;
}
Client::Client(Client&p)
{
clientNum++;
cout<<"第"<<clientNum<<"个客户创建"<<endl; serName=p.serName;
cout<<"Calling Constructing!"<<endl;
}
Client::~Client()
{
clientNum--;
cout<<"destructing!"<<endl;
}
void Client::ChangeServerName(string Name) {
serName=Name;
}
void Client::show()
{
cout<<serName<<" "<<clientNum<<endl;
}
//test.cpp
#include<iostream>
#include"client.h"
usingnamespace std;
int main()
{
Client c1;
c1.show();
c1.ChangeServerName("er");
c1.show();
c1.ChangeServerName("er");
Client c2(c1);
c2.show();
c2.ChangeServerName("qr");
c2.show();
c1.show();
return 0;
}
/5-12
#include<iostream>
using namespace std;
void fun()
{
staticinti=0;
i++;
cout<<"i="<<i<<endl;
}
int main()
{
for(inti=0;i<10;i++)
fun();
return 0;
}*/
//5-13友元的应用#include<iostream> using namespace std;
class X;
class Y
{
public:
void g(X*);
Y();
~Y();
private:
Y::Y()
{
}
Y::~Y()
{
}
class X
{
public:
X(){i=0;}
~X();
friend void h(X*);
friend void Y::g(X*);
friend class Z;
private:
inti;
};
X::~X()
{
}
void h(X*x)
{x->i+=10;}
void Y::g(X*x)
{x->i++;}
class Z
{
public:
Z();
~Z();
void fun(X*x)
{x->i+=5;} private:
Z::Z()
{
}
Z::~Z()
{
}
int main()
{
X x;
Z z;
z.fun(&x);
return 0;
}*/
#include<iostream>
using namespace std;
class Boat;
class Car
{
public:
Car(int j);
~Car();
friendintgetTotalWeight(Car &acar,Boat&aboat); private:
int weight;
};
Car::Car(int j)
{
weight=j;
}
Car::~Car()
{
}
class Boat
{
public:
Boat(int j);
~ Boat();
friendintgetTotalWeight(Car &acar,Boat&aboat); private:
int weight;
};
Boat:: Boat(int j)
{
weight=j;
}
Boat::~ Boat()
{
}
intgetTotalWeight(Car &acar,Boat&aboat)
{
returnacar.weight+aboat.weight;
}
int main()
{
Car c1(5);
Boat b1(6);
cout<<"total weight:"<<getTotalWeight(c1,b1)<<endl;
return 0;
}。

相关主题