浅谈C++继承中的名字查找

实例如下:

#include<iostream>
#include<string>
using namespace std;
class Base {
 public:
 void func() {
  cout << "func() in Base." << endl;
 }
 void func(int a) {
  cout << "func(int a) in Base." << endl;
 }
 void func(string s) {
  cout << "func(string s) in Base." << endl;
 }
};


class Derived : public Base { 
public:
 //using Base::func;
 void print() {
  cout << "func() in Derived." << endl;
 }
};


int main() {
 Derived d;
 d.Base::func();//指定基类版本
 d.func();
 d.func(12);//error,可在派生类中添加using Base::print;
 d.func("abc");//error,可在派生类中添加using Base::print;
 system("pause");
 return 0;
}
//一个对象,引用,指针的静态类型决定了该对象哪些成员可见。
//派生类作用域嵌套在基类作用域中
//派生类成员将屏蔽同名的基类成员
//如果派生类想通过自身类型使用的基类中重载版本,则派生类必须要么覆盖所有重载版本,要么一个也不覆盖。
//利用using声明可把基类中的所有重载版本都添加到派生类作用域中
//名字查找先于类型检查,如果在派生类中找到了调用的函数名,则不会继续向上查找,接着进行类型检查

以上这篇浅谈C++继承中的名字查找就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。