C++中继承的理解

Understanding Inheritance in C++

本问题已经有最佳答案,请猛点这里访问。

我正在努力学习C++,并编写了这个代码。根据我的理解,这段代码需要以"Derived Class"的形式生成输出,但输出是"Base Class"。请帮助我理解这一点。

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

class Base {
    public:
    char* name;
    void display() {
         cout << name << endl;
    }

};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Derived: public Base {
   public:
   char* name;
   void display() {
       cout << name <<"," << Base::name << endl;
   }
};

int main() {
   Derived d;
   d.name ="Derived Class";
   d.Base::name ="Base Class";

   Derived* dptr = &d;

   Base* bptr = dptr;

   bptr->display();
}

请把我当作一个初学者,解释一下为什么它的输出是"Base Class"


你需要制作display()方法virtual

这样地:

1
2
3
4
5
6
class Base{
    public:
    char* name;
    virtual void display() {
         cout << name << endl;
 }

virtual允许派生类"重写"基类函数。


多态性(通常与指向派生类实例的基类指针一起工作)是通过分派到虚拟函数来完成的,如其他答案中所述。但是,如果指向带有基类指针的派生类,则将使用该基类的数据成员,因为编译器不知道派生类的数据成员,而调用该基类的函数也是如此,因此基类display()函数使用基类name数据成员,结果是""基类"。


C++的调度有点奇怪。除非您声明显示方法"virtual",否则bptr->display将始终调用基类的display。

这里有更详细的解释


如果希望通过基类指针调用派生类函数,则需要使基类函数成为虚拟函数。将关键字virtual添加到函数中,您的代码就可以使用了。


http://www. PARASIFIF.COM/C++-FAQ/DYN-BIDENG.HTML

Non-virtual member functions are resolved statically. That is, the
member function is selected statically (at compile-time) based on the
type of the pointer (or reference) to the object.

In contrast, virtual member functions are resolved dynamically (at
run-time). That is, the member function is selected dynamically (at
run-time) based on the type of the object, not the type of the
pointer/reference to that object.