-2

下面是一个 C++ 代码:

#include<iostream>
using namespace std;
class Base {
    public:
          virtual int f() const { cout << "Base::f()\n"; }
          virtual void f(string) const {}
          virtual void g() const {}
};

class Derived4 : public Base {
    public:
          int f(int) const { cout << "Derived4::f()\n"; }
};
int main() {
    string s ("hello");
    Derived4 d4;
    Base *br = &d4; //line 5
    //br->f(1);//line 6
    br->f();//line 7
    br->f(s);//line 8
}

代码工作正常,但第 6 行出错。该代码正在调用 f() 的基本版本。我还读到如果你在派生类中重新定义函数,该函数的所有基类定义都隐藏了?我错了吗?

4

1 回答 1

2

有许多编译错误。搁置一旁——

多态性是一个运行时概念。因此,函数调用调度机制发生在运行时。您应该在基类和派生类中具有相同的成员函数签名才能使其工作。

br->f(1);//line 6

在编译时,编译器会尝试匹配Base. 在这种情况下,f(string)接受字符串类型,因此接受错误。

我还读到如果你在派生类中重新定义函数,该函数的所有基类定义都隐藏了?

那是一个不同的场景。

struct foo{
   fooBar(int i);
};

struct bar:foo{
   fooBar(std::string);
};

void test()
{
    bar obj;
    obj.fooBar(11); // bar class hides the member function foo::fooBar(int)
}
于 2013-06-25T19:14:08.587 回答