【一句话点破】基类/派生类的成员变量由哪个对象初始化的,哪个对象调用该成员变量时就用由它初始化的值 [尤其找准是基类对象or派生类对象的值]
【重要例题】15浙工大卷二读程序5题
·可运行代码如下
#include "bits/stdc++.h"
#include<iostream>
using namespace std;
class Base{int x0,y0;public:Base(int i,int j){ //基类2参构造 x0=i;y0=j;}void Move0(int x,int y){x0+=x; y0+=y;} void show0(){ cout<<"基类Base的x0为"<<x0<<",y0为"<<y0<<endl; }
};
class Derived:private Base{private:int x,y;public:Derived(int i,int j,int m,int n):Base(i,j){ //派生类构造初始参数列表 x=m; y=n;} void show0(){ cout<<"派生类Derived的x为"<<x<<",y为"<<y<<endl;} void Move1(){Move0(2,3);}void show1(){Base::show0();}
};int main(){ Base b(111,222); //x0=i=111,y0=j=222 b.show0(); //输出基类Base的x0为111,y0为222 Derived d(666,888,10,15); //x0=i=666,yo=j=888,x=m=10,y=n=15 d.Move1(); //【注意】执行基类move0(2,3),基类x0=x0+x=666+2,yo=yo+y=888+3 d.show0(); //输出派生类Derived的x为10,y为15 d.show1(); //【注意】调用基类show0(),输出类Base的x0,y0 return 0;
}