高手来解析下这题C++

来源:百度知道 编辑:UC知道 时间:2024/06/30 08:13:32
#include <iostream.h>
class Base
{
private:
int a,b;
public:
Base(int i,int j)
{
a=i;
b=j;
}
void move(int x,int y)
{
a+=x;
b+=y;
}
void show(){cout<<"a="<<a<<",b="<<b<<endl;}
};
class Derive:private Base
{
private:
int x,y;
public:
Derive(int i,int j,int k,int l):Base(i,j)
{
x=k;
y=l;
}
void show(){cout<<"x="<<x<<",y="<<y<<endl;}
void fun(){move(3,5);}
void showbase(){Base::show();}
};
void main()
{
Base b(1,2);
b.show();
Derive d(3,4,5,6);
d.fun();
d.show();
d.showbase();
}
输出: a=1,b=2
x=5,y=6
a=6,b=9
请问输出的最后一行为什么是a=6,b=9谢谢

Base b(1,2); // b: a=1 b=2
Derive d(3,4,5,6); // d: a=3 b=4 x=5 y=6

d.fun(); //执行move(3,5); move(3,5)就是 a=a+3;b=b+5 那么 d: a=6 b=9 x=5 y=6

d.showbase(); //就是将 d: a, b 打出

a=6 b=9! 明白了么。。

刷分走人 拜拜!

Derive d(3,4,5,6);的时候,会构建一个属于Derive的Base类,构造函数是 Base(3,4),之后执行 d.fun() 的时候,会调用 Base的move(3,5)函数,也就是在 Base(3,4)上,调用move(3,5),所以,a=6,b=9,在后面调用 d.baseshow()的时候,就显示 a=6,b=9了

当调用d.fun ();时,fun函数调用了一次move函数。作用是使a数据后移3个单位和b数据后移5个单位。原来a=3;b=4;现在后移了所以输出就是
a=6,b=9