47 lines
719 B
C++
47 lines
719 B
C++
|
// 继承中同名成员的处理方法
|
||
|
#include <iostream>
|
||
|
#include <cstring>
|
||
|
#include <cstdlib>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
class A
|
||
|
{
|
||
|
public:
|
||
|
int x;
|
||
|
A(int x) : x(x) {}
|
||
|
void show()
|
||
|
{
|
||
|
cout << "x = " << x << endl;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
class B : public A
|
||
|
{
|
||
|
private:
|
||
|
int x;
|
||
|
|
||
|
public:
|
||
|
// B(int x) : A(x)
|
||
|
// {
|
||
|
// // 就近原则: this->x 是 B 类的,不是父类 A 的
|
||
|
// this->x = x + 20;
|
||
|
// }
|
||
|
B(int x) : A(x), x(x + 20)
|
||
|
{
|
||
|
}
|
||
|
|
||
|
void showX()
|
||
|
{
|
||
|
cout << "x = " << x << endl;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
B b1(10);
|
||
|
b1.show(); // 从 A 类继承过来的方法,打印的是 A 类的 x
|
||
|
b1.showX(); // B 类自己的,打印自己的 a
|
||
|
return 0;
|
||
|
}
|