2014-03-03 111 views
0

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

回答

3

由于child::func隐藏base::func

您需要可以使其在派生类中可见的范围使名称:

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

或在调用点限定名称显式调用基版本:

c.base::func(2); 
+0

他们收到不同的参数。它们应该像重载一样进行操作(int变量会转到base/double变量以进入子进程)。并不是说我相信经过一个常数会产生任何可靠的结果。 – ciphermagi

+0

@ciphermagi名称隐藏背后有一个很好的理由 - [见这个答案](http://stackoverflow.com/questions/1628768/why-does-an-overridden-function-in-the-derived-class-hide-other -overloads的最)。 – jrok

1

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

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 not base :: func

+0

这里有一个有趣的帖子[自动转换方法参数](http://stackoverflow.com/questions/175689/can-you-use-keyword-explicit-to-prevent-automatic-conversion-of-method-参数) –

相关问题