填空题 [程序]
#include<iostream.h>
int n1=0,n2=0,n3=0,n4=0;
class T
{
public:
T(int a)
{
ia=a;
n1 ++;
}
void print()
{
cout<<ia<<endl;
}
int Getia()
{
return ia;
}
private:
int ia;
};
class S1:public T
{
int x;
public:
S1(int a,int c):T(a)
{
x=c;
n2 ++;
}
void printS1()
{
cout<<Getia()<<"/t"<<x<<endl;
}
};
class S2:public T
{
int y;
public:
S2(int a):T(10)
{
y=a;
n3 ++;
}
void printS2()
{
cout<<Getia()<<"/t"<<y<<endl;
}
};
class S:public S1,public S2
{
int xx;
public:
S(int a,float b,int c,int d):S1(a,b),S2(c)
{
xx=d;
n4 ++;
}
void prints()
{
cout<<xx<<endl;
}
};
void main(void)
{
T t1(2);
S1 t2(3,4);
S2 t3(5);
S t4(6,7,8,9),*p;
p=&t4;
p->printS();
p->printS1();
p->printS2();
cout<<n1<<"/t"<<n2<<"/t"<<n3<<"/t"<<n4<<endl;
}
执行以上程序后,输出的第二行是 1,第三行是 2,第四行是 3
【正确答案】
【答案解析】6 7;10 8;5 2 2 1 [解析] main函数创建类T对象t1(2),t1::ia=2,::n1=1;
main函数创建类S1对象t2(3,4),t2调用父类构造函数T(3),t2::s1::ia=3,::n1=2,t2::y=4,n2=1;
main函数创建类S2对象t3(5),t3调用父类构造函数T(10),t3::S1::ia=10,::n1=3,t3::y=5,n3=1;
main函数创建类S对象t4(6,7,8,9);
t4调用父类构造函数S1(6,7.0),调用S1父类构造函数T(6),t4::S1::T::ia=6,::n1=4,t4::S1::x=7,::n2=2;
t4调用父类构造函数S2(8),调用S2父类构造函数T(10),t4::S2:T::ia=10,::n1=5,t4::S2::y=8,::n3=2;
t4::xx=9,n4=1;
通过指针p调用t4.printS(),输出t4::S1::T::ia即6;
通过指针p调用t4.printS1(),即t4::S1 printS1();输出t4::S1::T::ia,即9;输出t4::S1::x,即7;
通过指针p调用t4.printS2(),即t4::S2 printS2();输出t4::S2::T::ia,即10;输出t4::S2::y,即8;
最后cout输出::n1、::n2、::n3、::n4,由上可知输出为5、2、2、1。