静态同名成员和非静态同名成员
静态同名成员: 1、通过对象访问 2、通过类名访问
#include <iostream>
using namespace std;
class BaseClass{
public:
BaseClass(){
m_A = 100;
}
int m_A;
void func(){
cout << "BaseClass void func " << endl;
}
//静态
static int m_B;
static void fun2(){
cout << "BaseClass static void fun2() " << endl;
}
};
int BaseClass::m_B = 100;
class MyClass:public BaseClass{
public:
MyClass(){
m_A = 200;
}
int m_A;
void func(){
cout << "MyClass void func " << endl;
}
//静态
static int m_B;
static void fun2(){
cout << "MyClass static void fun2() " << endl;
}
};
int MyClass::m_B = 200;
void test01(){
MyClass m1;
cout << "MyClass m_A为 " << m1.m_A << endl; //可以看到成员属性和成员函数都来自子类 这是因为子类会覆盖父类中的值
m1.func();
//现想使用父类中的 m_A 可以加上作用域
cout << "BaseClass m_A为 " << m1.BaseClass::m_A << endl;
m1.BaseClass::func();
}
void test02(){
MyClass m2;
cout << "MyClass static m_B为 " << m2.m_B << endl;
m2.fun2();
//1、通过对象访问
cout << "通过对象访问:" << endl;
cout << "BaseClass static m_B为" << m2.BaseClass::m_B << endl;
m2.BaseClass::fun2();
//2、通过类名访问
cout << "通过类名访问:" << endl;
cout << "BaseClass static m_B为" << MyClass::BaseClass::m_B << endl;
MyClass::BaseClass::fun2();//第一个::为类名,第二个为作用域
}
int main(){
// test01();
test02();
return 0;
}