【问题标题】:Usage of virtual keyword VS simple redefining in C++在 C++ 中使用虚拟关键字 VS 简单重新定义
【发布时间】:2019-02-03 05:11:32
【问题描述】:

我知道virtual 函数是在基类中声明的,并且可以(除非它是纯虚函数,否则不必)在派生类中进行细化。但是,我不明白重新定义虚函数和重新定义常规函数之间的区别。查看此示例代码:

class base {
public:
 virtual int getAge(){
  return 20;
 }
 int getId(){
  return 11111;
 }
};

class dri : public base{
public:
 int getAge(){
  return 30;
 }
 int getId(){
  return 222222;
 }
};

int main(){
 dri d;
 std:: cout << d.getAge() << std::endl;
 std:: cout << d.getId() << std::endl;
 return 0;
}

将输出:

30
222222

在这种情况下,virtual 关键字没有任何区别。这两个函数都被覆盖了。那么为什么需要它呢?

【问题讨论】:

  • @drescherjm 已添加
  • dri d; 替换为dri a; base&amp; d = a; 以查看区别。
  • 在您给出的示例main() 函数中,没有区别,因为编译器知道d 的类型为dri。还有其他一些例子,它确实有所作为。
  • 您确实提出了一个示例,说明承受virtual 方法的开销毫无意义。

标签: c++ inheritance


【解决方案1】:

您没有给出类成员函数调用的示例。我猜你写了以下代码:

dri sth;
cout << sth.getAge() << endl;
cout << sth.getId() << endl;

但是,请注意,c++ 的动态绑定和多态性只能在实例是指针或引用时应用,这实际上意味着您应该这样做以获得理想的输出:

base *sth = new dri();
cout << sth->getAge() << endl;
cout << sth->getId() << endl;

【讨论】:

    猜你喜欢
    • 2013-08-08
    • 2012-12-01
    • 1970-01-01
    • 2013-11-16
    • 2018-04-22
    • 2021-07-11
    • 1970-01-01
    • 2012-02-24
    相关资源
    最近更新 更多