c++ - 虚函数关键字

标签 c++ function inheritance virtual

“虚拟”关键字或不在子类中声明继承的虚函数之间有什么区别吗,考虑到我想调用适合我的对象的乐趣'类型。看看评论。

#include <cstdio>
struct A{
    int a;
    A():a(5){}
    virtual int fun(){return a+1;}
};
struct B: public A{
    virtual int fun(){return a+5;} //I put virtual here
//  int fun(){return a+5;} // Any difference if I put virtual before or not?
};
int main(){
    B obj;
    printf("%d\n", static_cast<A>(obj).fun()); // A::fun() called. Why?
    printf("%d\n", static_cast<A&>(obj).fun()); // B::fun() called. As expected
    printf("%d\n", static_cast<A*>(&obj)->fun()); // B::fun() called. As expected
    printf("%d\n", static_cast<A>(B()).fun()); // A::fun() again. Why?
//  printf("%d\n", static_cast<A&>(B()).fun()); //invalid_cast error. Why? 
    printf("%d\n", static_cast<A*>(&B())->fun()); //It works! B::fun() call
    return 0;
}

最佳答案

如果基类中的相应函数是虚拟的,则派生类中的覆盖函数被隐式声明为“虚拟”。只需确保您获得完全相同的签名,否则您可能会无意中隐藏原始函数并声明一个新函数!

在 C++0x 中,可以随意使用 override说明符。

你的两个“为什么?”问题是因为切片;你正在制作类型为 A 的新的复制切片对象.请注意,在 B x; static_cast<A>(x); Actor 阵容和说的一样A(x) .

关于c++ - 虚函数关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7054180/

相关文章:

c++ - 关于类(class)的问题

c++ - equal_to<key> boost::无序 multimap

c++ - 派生类构造函数参数无法访问 protected 基类成员

C++ 子类构造函数

c++ - 知道基类指针指向哪个派生类

java - java或c++中的邻接矩阵来查找连接的节点

c++ - 在 C++ 中访问矩阵时崩溃

r - 探测要在函数内部调用的全局变量

C++通过模板传递双数组

javascript - js - 检查函数是否完成