gpt4 book ai didi

c++ - virtual 关键字的使用 VS 在 C++ 中简单重定义

转载 作者:行者123 更新时间:2023-11-30 04:52:17 24 4
gpt4 key购买 nike

我知道 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 关键字没有任何区别。两个函数都被覆盖了。那么为什么需要它呢?

最佳答案

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

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

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

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

关于c++ - virtual 关键字的使用 VS 在 C++ 中简单重定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54500141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com