C++ 继承中同名成员变量和同名成员函数

 基类成员的作用域延伸到所有派生类

 派生类的重名成员屏蔽基类的同名成员

#include<iostream>
using namespace std;

class A
{
public:
	A(int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
		cout << "我是爸爸构造"<<  endl;
	}
	~A()
	{
		cout <<"我是爸爸析构" << endl;
	}
	void printfA()
	{
		cout << "爸爸b=" << b << endl;
	}
	int get()
	{
		return b;
	}
public:
	int a;
	int b;
};
class B :public A
{
public:
	B(int b = 0, int c = 0) :A(1,2)
	{
		this->b = b;
		this->c = c;
	}
	~B()
	{
		cout << "我是析构"<< endl;
	}
	void printfB()
	{
		cout <<"儿子b="<< b<< endl;
	}
	int get()
	{
		return b;
	}
public:
	int b;
	int c;
};

void main()
{
	B b1;
	A a1;
	//同名成员变量
	b1.b = 1;
	b1.A::b = 2;
	b1.printfA();
	b1.printfB();

	//同名成员函数
	cout << b1.get()<< endl;
	cout << b1.A::get()<< endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/error0_dameng/article/details/82219561