复习:
static修饰的变量,所有对象都共享同一份数据,编译阶段就初始化,类内声明,类外初始化
static函数:只能访问静态的成员变量,不能访问非静态的成员变量,所有对象都有含有同一份函数实例
#include<iostream>
#include<string>
using namespace std;
class Base {
public:
static int m_A;//创建一个静态成员
static void func()//创建一个静态成员函数
{
cout << "Base static func" << endl;
}
};
int Base::m_A = 100;//类外初始化
class Son:public Base
{
public:
static void func()//父类已经有了
{
cout << "Son static func" << endl;
}
static int m_A;//子类中创建一个同名静态成员
};
int Son::m_A = 200;//类外初始化
//同名成员属性
void test01()
{ //1.通过对象访问
cout << "同名成员属性" << endl;
cout << "通过对象访问:" << endl;
Son s;
cout <<"son m_A=" << s.m_A << endl;
cout << "Base m_A=" << s.Base::m_A << endl;
cout << "-----------------------------------"<<endl;
//2.通过类名访问
cout << "通过类名访问" << endl;
cout << "Base m_A=" << s.Base::m_A << endl;
}
//同名静态函数
void test02()
{ //1.通过对象访问
Son s1;
cout << "----------------------------------" << endl;
cout << "同名成员函数" << endl;
cout << "通过对象访问:" << endl;
s1.func();//子类调用子类func 直接 类名.函数名
s1.Base::func();//通过子类访问父类中的同名成员属性,需要加作用域
//2.通过类名访问
cout << "----------------------------------" << endl;
cout << "通过类名访问" << endl;//类名 + ::+同名函数名
Son::func(); //子类调用子类中func
Base::func(); //父类调用父类中func
Son::Base::func();//通过子类访问父类中的同名成员函数,需要加作用域
}
int main()
{
test01();
test02();
}