【问题标题】:Inheritance and polymorphism in C++C++中的继承和多态
【发布时间】:2014-02-01 00:44:11
【问题描述】:

我的问题是关于 C++ 中的继承和多态性。

class Base
{
public:
    virtual void f() { cout << "Base::f()" << endl; }
    void f(string s) { cout << "Base::f(string)" << endl; }
};

class Derivate1: public Base
{
public:
    void f() { cout << "Derivate1::f()" << endl; }
    void f(int i) { cout << "Derivate1::f(int)" <<endl; }

};

class Derivate2: public Base
{
public:
    void f() { cout << "Derivate2::f()" << endl; }
    void f(char c) { cout << "Derivate2::f(char)" << endl; }
};


int _tmain(int argc, _TCHAR* argv[])
{

//with base pointers
    Derivate1 d1;
    Derivate2 d2;
    Base *b1 = &d1;
    Base *b2 = &d2;

    b1->f();           //output: Derivate1::f() ok.
    b1->f("string");   //output: Base::f(string) ok.
    b1->f(1);        //error !

    b2->f();           //output: Derivate2::f() ok.
    b2->f("string");   //output: Base::f(string) ok.
    b2->f('c');      //error !

//with direct derivate object
    d1.f();           //output: Derivate1::f() ok.
    d1.f("string");   //error !
    d1.f(1);          //output: Derivate1::f(int) ok.

    d2.f();           //output: Derivate2::f() ok.
    d2.f("string");   //error !
    d2.f('c');        //output: Derivate2::f(char) ok.

return 0;
}

如果我想在派生对象中使用可访问的基类中的重新定义函数,我必须做什么?我不想在派生类中使用Base::f;

【问题讨论】:

标签: c++ inheritance polymorphism


【解决方案1】:

在这种情况下,您需要告诉 C++ 您希望在派生类中包含 f 的基类定义。这是通过using 语句完成的

class Derivate1: public Base
{
public:
  using Base::f;
  ...
};

class Derivate2: public Base
{
public:
  using Base::f;
  ...
};

这实质上是告诉 C++ 编译器在进行名称查找时同时包含 f 的派生类和父类定义。如果没有这个,C++ 编译器将基本上停止在层次结构中的第一个类型,它有一个名为f 的成员,并且只考虑在该类型中声明的重载。

【讨论】:

  • 这仅适用于直接派生对象访问,不适用于基指针。
  • @RaduGabor 您对基指针的问题是您无法按照您尝试的方式“注入”新方法。如果要通过基指针调用方法,则必须在基类中声明它。 using 是您其他情况的正确解决方案。
【解决方案2】:

C++ 通常对这种类型的继承非常严格,如果您想解决问题,可以使用它来解决类似 d1.f(); 的问题:

static_cast<Base*>(&d1)->f("string");

如果你想拨打这样的电话:b1-&gt;f(1); 好吧.. 你不能。这就是多态性的全部意义所在。您必须在 Base 类中声明一个虚拟方法,该类具有名为 f(int i) 的方法,以便编译器可以链接 Base 类方法和 Derivate1 类方法:

class Base
{
public:
  //...
    virtual void f(int i) { printf("Base::f(int)"); }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    相关资源
    最近更新 更多