C++ 使用 using 声明语句放开基类的重载函数

一万年太久 / 2024-08-24 / 原文

#include <string>
#include <iostream>

using namespace std;

namespace
{
    class Animal
    {
    public:
        string GetInfo()
        {
            return "我是动物";
        }
    };

    class Dog :public Animal
    {
    public:
        using Animal::GetInfo;
        string GetInfo(string exta)
        {
            return "我是动物:" + exta;
        }
    };
}
#if 1

int main()
{
    Dog dog;
    //cout << dog.Animal::GetInfo() << endl;
    cout << dog.GetInfo() << endl;
    cout << dog.GetInfo("狗") << endl;

    return 0;
}

#endif

输出:

我是动物
我是动物:狗

如果不是使用using语句声明,就需要用显式的域来访问:dog.Animal::GetInfo()