c – 明确解决类成员的范围
发布时间:2020-12-16 10:09:53 所属栏目:百科 来源:网络整理
导读:请考虑以下示例: #include iostreamstruct foo { void fun() const { std::cout "foo::fun()" std::endl; }};auto main() - int { foo f; f.fun(); f.foo::fun(); return 0;} DEMO 如上例所示,成员函数foo :: fun()以两种不同的方式引发. 在第二次调用(即f.
请考虑以下示例:
#include <iostream> struct foo { void fun() const { std::cout << "foo::fun()" << std::endl; } }; auto main() -> int { foo f; f.fun(); f.foo::fun(); return 0; } DEMO >如上例所示,成员函数foo :: fun()以两种不同的方式引发. 问题: >两个电话之间的区别是什么(即f.fun()和f.foo::fun())? 解决方法
一个区别是,如果fun()是一个虚函数,那么第二种方式调用它会抑制虚拟调度.
struct foo { void virtual fun() const { std::cout << "foo::fun()" << std::endl; } }; struct bar : foo { void fun() const override { std::cout << "bar::fun()" << std::endl; } }; auto main() -> int { bar b; foo *f = &b; f->fun(); f->foo::fun(); } 输出: bar::fun() foo::fun() Live demo 同样,如果您反而从基类隐藏了一个函数,它允许您访问基类版本. struct foo { void fun() const { std::cout << "foo::fun()" << std::endl; } }; struct bar : foo { void fun(int) const { std::cout << "bar::fun()" << std::endl; } }; auto main() -> int { bar b; b.fun(10); b.foo::fun(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |