【问题标题】:C++ function overloading and dynamic binding compile problem [duplicate]C ++函数重载和动态绑定编译问题[重复]
【发布时间】:2010-04-22 05:09:06
【问题描述】:

可能的重复:
C++ method only visible when object cast to base class?!
Why does an overridden function in the derived class hide other overloads of the base class?

#include <iostream>

using namespace std;

class A
{
public:
    virtual void foo(void) const { cout << "A::foo(void)" << endl; }
    virtual void foo(int i) const { cout << i << endl; }
    virtual ~A() {}
};

class B : public A
{
public:
    void foo(int i) const { this->foo(); cout << i << endl; }
};

class C : public B
{
public:
    void foo(void) const { cout << "C::foo(void)" << endl; }
};


int main(int argc, char ** argv)
{
    C test;

    test.foo(45);

    return 0;
}

上面的代码不能编译:

$>g++ test.cpp -o test.exe
test.cpp: In member function 'virtual void B::foo(int) const':
test.cpp:17: error: no matching function for call to 'B::foo() const'
test.cpp:17: note: candidates are: virtual void B::foo(int) const
test.cpp: In function 'int main(int, char**)':
test.cpp:31: error: no matching function for call to 'C::foo(int)'
test.cpp:23: note: candidates are: virtual void C::foo() const

如果方法“foo(void)”更改为“goo(void)”,则编译。为什么会这样?不改变“foo(void)”的方法名是否可以编译代码?

谢谢。

【问题讨论】:

标签: c++ inheritance overloading dynamic-binding


【解决方案1】:

问题是,继承不是通过不同的命名空间进行的。所以要让它编译,你必须用 using 指令告诉编译器:

class B : public A
{
public:
    using A::foo;
    void foo(int i) const { this->foo(); cout << i << endl; }
};

class C : public A
{
public:
    using B::foo;
    void foo(void) const { cout << "C::foo(void)" << endl; }
};

【讨论】:

  • 应该重载而不是继承?
  • @devil:取决于你在做什么,尽管这些概念并不真正相关。
  • @Gman:编译错误不仅仅发生在继承上。例如。如果 foo(void) 更改为 goo(void) 那么只有继承。当继承与重载 foo 方法名称结合使用时,就会发生这种情况。尽管这些概念是不相关的,但似乎它们在语言实现中是相关的,因为如果其中任何一个被子类覆盖,则默认情况下不会继承重载函数。
  • @devil:更准确地说,当查找规则遇到与正在查找的标识符匹配的第一个标识符时,它们将停止查找层次结构。您可以从派生对象中调用隐藏方法:myderived.base::foo(),并且该方法可用于派生类型,但您必须提示编译器,因为使用常规查找规则将无法找到它。
【解决方案2】:

foo goo void int


我可能错了,但这可能只是问题所在:

阴影仅基于名称,而不是参数的类型。编译器观察到派生类中有一个具有正确名称的函数,它停止查找。选择上下文后,它会在派生类中查找适用的重载,但没有找到,因此报告错误。

更多详情在这里
C++ method only visible when object cast to base class?


C 类 有一个 foo(void)

ma​​in() 中使用:

test.foo(45);

您将 int 传递给 foo 函数,即使它是 foo(void)
因此错误:

test.cpp: In function 'int main(int, char**)':  
test.cpp:31: error: nomatching function for call to'C::foo(int)'

我希望我说得通。
是这个吗??评论任何人??...

【讨论】:

  • 不,不是。请参阅问题的 cmets 以获得正确答案。
  • 实际上,我认为问题更多与第 17 行中的“this->foo()”有关。即,如果将 foo(void) 更改为 goo(void),则第 31 行不是一个问题。
猜你喜欢
  • 2014-03-07
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
相关资源
最近更新 更多