考虑以下示例:
#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.foo::fun()
),成员类foo::fun()
的作用域是明确的消除歧义/解决。
问题:
- 这两个调用(即
f.fun()
和f.foo::fun()
)有什么区别? - 通过显式消除其范围与以经典方式调用成员函数或可公开访问的成员变量的歧义,调用成员函数或可公开访问的成员变量是否有任何优势?
- 通过显式消除范围歧义来调用成员函数或可公开访问的成员变量是否存在任何缺陷?
最佳答案
一个区别是,如果 fun()
是一个 virtual
函数,以第二种方式调用它会抑制虚拟调度。
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()
类似地,如果您从基类中隐藏一个函数,它允许您访问基类版本。
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();
}
关于c++ - 显式解析类成员的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24295458/