虚函数关键字

发布于 2024-11-29 11:21:15 字数 918 浏览 0 评论 0原文

考虑到我想调用适合我的对象类型的 fun ,在子类中声明继承的虚函数与“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;
}

Is there any difference between declaring inherited virtual function in a child class with the "virtual" keyword or not, considering I want to call fun appropriate to my objects' type. Look at the comments.

#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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月静好 2024-12-06 11:21:15

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

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

你的两个“为什么?”问题是因为切片;您正在创建 A 类型的新的复制切片对象。请注意,在 B x; 中static_cast(x); 转换与 A(x) 相同。

Overriding functions in derived classes are implicitly declared "virtual" if the corresponding function in the base class is virtual. Just make sure you got the exact same signature, or you might inadvertently hide the original function and declare a new one!

In C++0x, feel free to make liberal use of the override specifier.

Your two "Why?" questions are because of slicing; you're making new, copy-sliced objects of type A. Note that in B x; static_cast<A>(x); the cast is the same as saying A(x).

酒中人 2024-12-06 11:21:15

在派生类中重写的成员函数之前保留virtual关键字是可选的。运行时多态性仅适用于指针或引用。

Keeping the virtual key word before the overridden member function in the derived class is optional. Run-time polymorphism works only for pointers or references.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文