每个类定义自己的作用域,当存在继承关系时,派生类的作用域嵌套在其基类的作用域中。
(1)一个对象、引用或指针的静态类型决定了该对象的哪些成员是可见的,即使静态类型与动态类型不一致(当使用基类的引用或指针时,会发生这种情况)。
(2)派生类的成员将隐藏同名的基类成员, 使用作用域来使用一个被隐藏的基类成员
(3)名字查找先于类型检查
#include <iostream>
using namespace std;
class base
{
public:
base(int a, int b)
{
this->a = a;
this->b = b;
}
void print()
{
cout << "我是基类" << endl;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
void method()
{
cout << "我是基类中的方法,哈哈" << endl;
}
protected:
int a;
private:
int b;
};
class Derived : public base
{
public:
Derived(int m, int n) :base(m,n)
{
a = 0;
b = 0;
}
public:
void print2()
{
cout << "我是子类" << endl;
}
int getA()
{
return a;
//return base::a;
}
int getB()
{
return b;
}
void method(int i)
{
cout << "我是子类中的方法,哈哈 " << i << endl;
}
protected:
int a;
private:
int b;
};
int main()
{
Derived d(1,2);
Derived *pd = &d;
base *pb = &d;
/* 一个对象、引用或指针的静态类型决定了该对象的哪些成员是可见的 */
pd->print(); //调用父类中的函数
pb->print();
cout << endl;
pd->print2();
//pb->print2(); //error C2039: “print2”: 不是“base”的成员,编译通不过
cout << endl;
/* 派生类的成员将隐藏同名的基类成员 */
cout << pd->getB() << endl;
cout << pb->getB() << endl;
cout << endl;
/* 使用作用域来使用一个被隐藏的基类成员 */
cout << pd->getA() << endl;
cout << pb->getA() << endl;
cout << d.base::getA() << endl;
cout << endl;
/* 名字查找先于类型检查 */
base b(10,20);
b.method();
d.method(30);
// d.method(); //错误:参数列表为空的method被隐藏了
d.base::method(); //使用作用域运算符
cout << endl;
system("pause");
return 0;
}
测试结果: