当前位置:文档之家› 实验二类和对象

实验二类和对象

实验二类和对象
1.实验目的:
(1) 掌握Visual C++6.0基本操作
(2) 了解C++程序运行环境;
(3) 掌握简单的C++程序的开发过程(编辑、编译、连接和运行)。

(4) 掌握类及其成员的定义方法;
(5) 掌握对象的创建方法;
2.实验内容:
2.1按要求分析程序指出程序运行的结果:
1)分析下面的程序,并给出程序运行的结果:
#include<iostream.h>
class change
{char c1,c2;
public:
void set(char a){c2=((c1=a)-32);}
void print()
{cout<<c1<<" can be upwritten as "<<c2<<endl;}
};
void main()
{change a,b;
a.set('a');
b.set('b');
a.print();
b.print();
}
运行结果:
a can be upwritten as A
b can be upwritten as B
Press any key to continue
程序分析:
由主函数可知,创建的类名为change,两个类对象为a,b,类中含有两个公有成员函数set(char a)和print(),利用函数set(char a)对两个私有成员数据赋值,即为减数与被减数的数值,利用函数print()对两个运算后的类对象进行输出。

2)分析下面的程序,并给出输出结果:
#include<iostream.h>
class pair
{char c1,c2;
public:
void set(char b)
{c1=1+(c2=b);}
unsigned where_am_I()
{return((unsigned)this);}
{cout<<c1<<"+"<<c2<<"\t";}
};
void main()
{pair a,b,c;
a.set('A');
b.set('B');
c.set('C');
a.print();
cout<<"is at "<<a.where_am_I()<<'\n';
b.print();
cout<<"is at "<<b.where_am_I()<<'\n';
c.print();
cout<<"is at "<<c.where_am_I()<<'\n';
}
运行结果:
B+A is at 1245052
C+B is at 1245048
D+C is at 1245044
Press any key to continue
程序分析:
由主函数可知,创建的类名为pair,三个类对象为a,b,c,类中含有,三个公有成员函数set(char b)和where_am_I()和print(),利用函数set(char b)对两个私有成员数据赋值,利用函数where_am_I() this 是一个指针,这个返回语句的功能是把this指针指向的对象的地址用无符号数的类型返回。

例如如果this 指向对象的地址是0x0000ffff,则返回值就是这个。

+ 利用函数print()对两个运算后的类对象进行输出。

2.2编写并调试程序:
1)下面是一个类的测试程序,给定主函数,请写出类的定义,构成一个完整的程序,使执行程序后输出结果为:88-32=56
给定的主函数为:
void main()
{
Tst t;
t.init(88,32);
t.print();
}
2)编程分析
由主函数可知,要创建的类名为Tst,一个类对象为t,类中含有两个公有成员函数init()和print(),利用函数init()对两个私有成员数据赋值,即为减数与被减数的数值,为了程序的实现需要定义第三个成员数据作为减法之差。

#include<iostream.h>
class Tst
{ int x,y,z;
public:
void init(int a,int b){
z=((x=a)-(y=b));
}
void print()
{cout<<x<<"-"<<y<<"="<<z<<endl;} };
void main()
{
Tst t;
t.init(88,32);
t.print();
}
4)运行结果
88-32=56
5)调试情况分析
3.实验结论:。

相关主题