为什么在 SO SIUTATION 中无法访问基类的成员函数?

why can't access member function of base class in thus siutation?

本文关键字:基类 成员 函数 访问 SO SIUTATION 为什么      更新时间:2023-10-16

我很困惑,为什么我无法访问void func(int i),有人可以帮助我吗?当然,这只是一个演示,以帮助您轻松理解我的问题。它的真实代码很大,我希望 Base 和 Child 中的成员函数都可用。

输出始终为**

double
2

**

        struct base
        {
            void func(int i)
            {
                cout << "int" << endl;
                cout << i << endl;
            }
        };
        struct child : base
        {
            void func(double d)
            {
                cout << "double" << endl;
                cout << d << endl;
            }
        };
        child c;
        c.func((int)2);

因为child::func隐藏了base::func .

您需要通过将名称置于作用域中来使其在派生类中可见:

struct child : base
{
    using base::func;
     void func(double d)
     {
         cout << "double" << endl;
         cout << d << endl;
     }
};

或者通过在调用站点限定名称来显式调用基本版本:

c.base::func(2);

从 int 到 double 的隐式转换掩盖了实际问题。如果将基类 func 参数类型从 int 更改为字符串:

struct base
{
    void func(string i)
    {
        cout << "string" << endl;
        cout << i << endl;
    }
};

然后,您将收到以下错误以使其更清晰:

func.cpp: In function `int main()':
func.cpp:27: error: no matching function for call to `child::func(const char[13])'
func.cpp:17: note: candidates are: void child::func(double)

在你可以看到它的地方只有子::func而不是base::func的可见性::func