【问题标题】:why can't access member function of base class in thus siutation?为什么在这种情况下不能访问基类的成员函数?
【发布时间】:2014-03-03 10:05:03
【问题描述】:

我很困惑,为什么我无法访问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);

【问题讨论】:

    标签: c++ visual-studio-2010 visual-c++


    【解决方案1】:

    因为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 变量转到 base / double 变量转到 child)。并不是说我相信传递一个常数会产生任何可靠的结果。
    • @ciphermagi 隐藏名称是有充分理由的 - see this answer
    【解决方案2】:

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

    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)
    

    你可以看到它只有 child::func 的可见性而不是 base::func

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    相关资源
    最近更新 更多