C++ 继承中的同名成员的情况01

class Base
{
public:
	Base()
	{
		this->m_A = 100;
	}
	void func()
	{
		cout << "Base中的Func调用" << endl;
	}
	void func(int a)
	{
		cout << "Base中的Func(int a)调用" << endl;
	}

	int m_A;
};
class Son : public Base
{
public:
	Son()
	{
		this->m_A = 200;
	}
	void func()
	{
		cout << "Son中的Func调用" << endl;
	}
	int m_A;
};
void test01()
{
	Son s;
	cout << s.m_A << endl; //调用Son类的 m_A 
	cout << "Base中的m_A " << s.Base::m_A << endl; //调用Base类中的m_A
	//同名的成员函数 ,子类会隐藏掉父类中的所有版本
	s.func();//调用Son类的 func 
	s.Base::func(10);//调用Base类的 func 
}

int main(){
	test01();
}

继承中的同名成员处理
1如果子类和父类拥有同名成员
2优先调用子类的成员,可以通过作用域调用父类的成员
3同名的成员函数 ,子类会隐藏掉父类中的所有版本,如果想调用父类中的其他版本,加上作用域即可


class Base
{
public:
	static int m_A; // 共享数据,编译阶段分配内存,类内声明,类外初始化
	static void func()
	{
		cout << "Base中的func调用" << endl;
	}
	static void func(int a)
	{
		cout << "Base中的func(int a)调用" << endl;
	}
};
int Base::m_A = 10;
class Son :public Base
{
public:
	static int m_A;
	static void func()
	{
		cout << "Son中的func调用" << endl;
	}
};

int Son::m_A = 20;
void test01()
{
	//对m_A进行访问
	Son s;
	cout << "son中的m_A = "<<  s.m_A << endl;
	cout << "base中的m_A = " << s.Base::m_A << endl;

	//通过类名进行访问
	cout << "通过类名访问 son中的m_A = " << Son::m_A << endl;
	cout << "通过类名访问 base中的m_A = " << Son::Base::m_A << endl;

	//同名成员函数 进行调用
	s.func();
	Son::func();
	//子类中同名成员函数 会隐藏掉父类中所有同名成员函数的重载版本,可以通过类名访问到父类中的其他版本
	s.Base::func(1);
	Son::Base::func(1);
}
int main(){
	test01();
}

10继承中的同名静态成员处理
10.1如果子类和父类拥有同名成员
10.2优先调用子类的成员,可以通过作用域调用父类的成员
10.3同名的成员函数 ,子类会隐藏掉父类中的所有版本,如果想调用父类中的其他版本,加上作用域即可
10.4访问方式有两种:
10.4.1一种通过对象进行访问
10.4.2另一种通过类名进行访问

发布了100 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43903378/article/details/103943734