#include <iostream>
using namespace std;
class base
{
private:int x;
public:base(int a){x=a;}
int get( ){return x;}
void showbase( ) {cout<<"x="<<x<<endl;}
};
class Derived:public base

完成程序题:请按试题顺序和空格顺序填写答案。


#include <iostream>
using namespace std;
class base
{
private:int x;
public:base(int a){x=a;}
int get( ){return x;}
void showbase( ) {cout<<"x="<<x<<endl;}
};
class Derived:public base
{private:int y;
public:Derived(int a,int b):base(a) {y=b;}
void showderived( )
{cout<<"x="<<get()<<",y="<<y<<endl;}
};
void main()
{
base b(3);
Derived d(6,7);
b.showbase( );
d.showderived( );
__________________;
b.showbase( );

__________________;
b1.showbase( );
base * pb=&b1;’
pb->showbase( );
d.showderived( );
b.showbase( );
}
输出结果如下:
x=3
x=6,y=7
x=6
x=6
x=6
x=6,y=7
x=6


【正确答案】:

第1空:B=D;
第2空:BASE &B1=B;


【题目解析】:

在C++中,“引用”的定义格式如下:
类型名 &引用名=同类型的某变量名;

如果给某个变量起了别名,相当于变量和这个引用都对应到同一地址。

根据题目
base b(3);
Derived d(6,7);构造出b,d对象。
执行结果
bshowbase( ); 即输出 x=3

d.showderived( );即输出x=6,y=7
b.showbase( )输出x=6,可执行b=d;即将d的值赋值给b,输出x=6 

为创建b1,因此base &b1=b;b1.showbase(),输出x=6
pb->showbase( );类对象的指针可以通过“->”运算符访问对象的成员,输出为x=6
d.showderived( );d值未改变,输出x=6,y=7
b.showbase( );b值改变,输出x=6



Top