使用VC6打开考生文件夹下的工程test12_1,此工程包含一个源程序文件test_12.cpp,但该程序运行有问题,请改正程序中的错误,使该程序的输出结果如下:
fun (Sample &p) 1 2
fun (Sample *p) 3 4
20 10
源程序文件test12_1清单如下:
#include<iostream .h>
class Sample
private:
int x,y;
static int z;
public:
Sample(int a,int b) x=a;y=b;
void fun(Sample &p);
void fun(Sample *p);
static void print(Sample s);
;
/*************** found ***************/
int z=10;
void Sample::fun(Sample &p)
x=p.x;y=p.y;
cout<<"fun(Sample &p)"<<" "<<x<<" "<<y<<endl;
void Sample::fun(Sample *p)
/************** found **************/
x=p.x; y=p.y;
cout<<"fun(Sample *p) "<<" ’<<x<<" "<<y<<endl;
void Sample::print (Sample s)
/*************** found *****************/
x=20;
cout<<s. x<<" "<<z<<endl;
void main()
Sample p(1,2),q(3,4);
p. fun(p);
p. fun(&q);
p. print(p);
参考答案:
(1)错误:int z=10;
正确:int Sample::z=10;
(2)错误:x=p.x;y=p.y;
正确;x=p->x;y=p->y;
(3)错误:x=20;
正确;s.x=20;
解析:
(1)主要考查考生对于静态成员初始化定义的理解,静态成员使用关键字static修饰,应对其进行类体外初始化,格式为数据类型“类名::静态变量名:初始值”;
(2)主要考查考生对于指针与引用区别的掌握,x和y都是指针类型的变量,应使用“->”调用类的成员;
(3)主要考查考生对于静态成员函数的掌握,在静态成员函数中使用非静态成员,需要用对象来引用。