一. 子类访问子类同名的成员,直接访问即可。
#include <iostream>
using namespace std;
class Base {
public:
Base(int age = 0) : m_age(age) {}
int get_age() {return m_age;}
static int get_counter() {return ms_counter;}
int m_age;
static int ms_counter; // 静态成员,类内声明,内外初始化
};
int Base::ms_counter = 55; // 内外初始化
class Derived : public Base {
public:
Derived(int age = 0, int base_age = 0) : Base(base_age), m_age(age) {}
int get_age() {return m_age;}
static int get_counter() {return ms_counter;}
int m_age;
static int ms_counter;
};
int Derived::ms_counter = 50; // 内外初始化
int main(int argc, char *argv[]) {
// 通过对象访问非静态和静态成员
Derived child(10, 40);
cout << "child age = " << child.m_age << endl;
cout << "child age = " << child.get_age() << endl;
cout << endl;
cout << "child counter = " << child.ms_counter << endl;
cout << "child counter = " << child.get_counter() << endl;
// 通过类名访问静态成员
cout << "Derived::counter = " << Derived::ms_counter << endl;
cout << "Derived::counter = " << Derived::get_counter() << endl;
return 0;
}
二. 子类访问父类同名的成员,需加父类作用域。
因为:
1.子类中出现和父类同名的成员变量,子类会屏蔽掉父类的同名成员变量。
2.子类中出现和父类同名的成员函数,子类会屏蔽掉父类中跟子类同名的所有函数(包括重载的所有版本)。
#include <iostream>
using namespace std;
class Base {
public:
Base(int age = 0) : m_age(age) {}
int get_age() {return m_age;}
static int get_counter() {return ms_counter;}
int m_age;
static int ms_counter; // 静态成员,类内声明,内外初始化
};
int Base::ms_counter = 55; // 内外初始化
class Derived : public Base {
public:
Derived(int age = 0, int base_age = 0) : Base(base_age), m_age(age) {}
int get_age() {return m_age;}
static int get_counter() {return ms_counter;}
int m_age;
static int ms_counter;
};
int Derived::ms_counter = 50; // 内外初始化
int main(int argc, char *argv[]) {
// 通过对象访问非静态和静态成员
Derived child(10, 40);
cout << "base age = " << child.Base::m_age << endl;
cout << "base age = " << child.Base::get_age() << endl;
cout << endl;
cout << "base counter = " << child.Base::ms_counter << endl;
cout << "base counter = " << child.Base::get_counter() << endl;
// 通过类名访问静态成员
cout << "Base::counter = " << Derived::Base::ms_counter << endl;
cout << "Base::counter = " << Derived::Base::get_counter() << endl;
return 0;
}