简体   繁体   English

从基类指针调用子类方法?

[英]Calling sub-class method from a base-class pointer?

I didn't know what to give as a title, I expect more experienced stackoverflow.com users to improve it. 我不知道该给什么标题,我希望更多有经验的stackoverflow.com用户可以改善它。

Let's say we have the class A 假设我们有A类

class A {
  void hello(){  cout << "i'm an A" << endl; }
}

and its sub-class B 及其子类别B

class B: public A {
  void hello(){  cout << "i'm a B" << endl; }
}

Then we did somewhere in our program 然后我们在程序中的某处做了

A* array[2];
array[0] = new A;
array[1] = new B;
array[0]->hello(); // output: "i'm an A"
array[1]->hello(); // output: "i'm a B"

why doesn't the array[1].hello(); 为什么没有array[1].hello(); output I'm a B since we instanciated a B object for that base-class pointer ? 输出I'm a B因为我们为该基类指针实例化了一个B对象? and how to make it happen ? 以及如何实现?

You have to make hello a virtual function: 您必须将hello设为虚拟函数:

class A {
    virtual void hello() { cout << "i'm an A" << endl; }
};

class B : public A {
    virtual void hello() override { cout << "i'm a B" << endl; } // 1) 
};

This tells the compiler that the actual function should not be determined by the static type (the type of the pointer or reference) but by the dynamic (run-time) type of the object. 这告诉编译器,实际功能不应由静态类型(指针或引用的类型)确定,而应由对象的动态(运行时)类型确定。

1) The override keyword tells the compiler to check, if the function actually overrides a hello function in the base class (helps eg to catch spelling mistakes or differences in the parameter types). 1) override关键字告诉编译器检查该函数是否实际上覆盖了基类中的hello函数(有助于例如捕获拼写错误或参数类型的差异)。

Couple of changes here: 这里有几个变化:

make function hello in class A, a virtual and public: because by default it is private 在类A( virtualpublic:中使函数hello public:因为默认情况下它是private

class A {
public: 
virtual void hello(){ cout << "i'm an A" << endl; }
};

Similarly make hello in class B virtual 类似地,使B类中的virtual问候

class B: public A {
virtual void hello(){  cout << "i'm a B" << endl; }
};

Since you have inherited class A in class B, derived class B will call the function from the Base class. 由于您已经继承了类B中的类A,因此派生类B将从基类中调用该函数。 You need to override the function in class B, as you want to change the Base class functionality. 要更改基类功能,您需要重写B类中的函数。

You can do this with the override and virtual keywords. 您可以使用override和virtual关键字执行此操作。

http://en.cppreference.com/w/cpp/language/override http://en.cppreference.com/w/cpp/language/override

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM