明确地解析类成员的作用域 [英] Resolving explicitly the scope of a class member
本文介绍了明确地解析类成员的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下示例:
#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()
有两种不同的方式。DEMO
As shown in the above example, member function
foo::fun()
is evoked with two different ways.,
f.foo::fun()
),成员类foo :: fun()
消歧/解决。In the second call (i.e.,
f.foo::fun()
), the scope of member classfoo::fun()
is explicitly disambiguated/Resolved.问题:
- 两个调用之间的区别是什么(即
f.fun()
和f.foo::fun )
)? - 调用成员函数或可公开访问的成员变量是否有明显消除其范围的优势, / li>
- 通过显式地消除其范围,调用成员函数或可公开访问的成员变量是否有任何陷阱?
- What's the difference between the two calls (i.e.,
f.fun()
andf.foo::fun()
)? - Are there any advantages in calling a member function or a publicly accessible member variable by explicitly disambiguating its scope against calling it in the classical way?
- Are there any pitfalls in calling a member function or a publicly accessible member variable by explicitly disambiguating its scope?
推荐答案
一个区别是如果
fun()
是virtual
function,第二种方式会禁止虚拟分派。One difference is that if
fun()
were avirtual
function, calling it the second way would inhibit virtual dispatch.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()
同样,如果你是从基类隐藏一个函数,它允许你访问基类版本。
Similarly if you were instead hiding a function from the base class, it allows you to access the base class version.
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(); }
这篇关于明确地解析类成员的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 两个调用之间的区别是什么(即
查看全文