【问题标题】:virtual method in base class and non virtula method in child class. Still how child class method is called even if its is non-virtual [duplicate]基类中的虚方法和子类中的非虚方法。即使它是非虚拟的,仍然如何调用子类方法[重复]
【发布时间】:2017-11-11 07:36:35
【问题描述】:

我正在查看下面提到的一段代码,发现子类中的方法是非虚拟的,但该方法仍然被其基类指针调用。谁能告诉我为什么……??

class Base {
    virtual void method() { std::cout << "from Base" << std::endl; }
public:
    virtual ~Base() { method(); }
    void baseMethod() { method(); }
};

class A : public Base {
    void method() { std::cout << "from A" << std::endl; }
public:
    ~A() { method(); }
};


int main(void) {
    Base* base = new A;
    base->baseMethod();     
    getchar();
    return 0;       
}

输出 - 来自 A

【问题讨论】:

  • virtual 关键字在派生类中是可选的。
  • 虚拟一次 - 永远虚拟...没有办法“去虚拟化”方法。
  • 这是否意味着子类中的虚拟关键字是可选的?

标签: c++ inheritance polymorphism overriding virtual-functions


【解决方案1】:

派生类中重写虚方法的方法也将是virtual;这与关键字virtual是否用于它无关。

那么 Derived 类中的这个函数也是虚拟的(无论在其声明中是否使用关键字 virtual)并覆盖 Base::vf(无论在其声明中是否使用单词 override)。

【讨论】:

  • 最好包括引用该引文的来源。
  • @MartinBonner 我把链接放在“虚拟”这个词上。 ?
猜你喜欢
  • 2015-06-13
  • 2020-10-21
  • 2011-01-05
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 2018-06-12
相关资源
最近更新 更多