为什么::(作用域)与空左操作数一起使用
Why is :: (scope) used with empty left-hand operand?
我已经看到这种情况好几次了,我一直在挠头想知道为什么…
例如:(http://www.codeguru.com/forum/showthread.php?t=377394)
void LeftClick ( )
{
INPUT Input={0};
// left down
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
::SendInput(1,&Input,sizeof(INPUT));
// left up
::ZeroMemory(&Input,sizeof(INPUT));
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
::SendInput(1,&Input,sizeof(INPUT));
}
这个例子没有::(scope)操作符也可以工作,那么为什么还要使用它们呢?
这基本上意味着"获取全局作用域的函数,而不是当前可见的函数"。
void SendInput() { /* (1) */
}
namespace derp {
void SendInput() { /* (2) */
}
void LeftClick() {
...
::SendInput(); /* matches (1) */
SendInput(); /* matches (2) */
}
}
假设您有以下内容:
void bar()
{
}
struct Foo
{
void bar();
};
如果你想从成员函数Foo::bar
中调用全局函数bar
,你可以使用左边为空的语法:
void Foo::bar()
{
// Call the global bar function, not recursively call myself
::bar();
}
强制绝对名称解析。
如果没有它,则相对于类/函数命名空间路径搜索名称解析。
假设LeftClick()在命名空间层次结构中:
namespace Level1
{
namespace Level2
{
namespace Level3
{
LeftClick()
{
::SendInput(); // Absolute path only. SendInput in global namespace
SendInput(); // Relative path (Note resolved at compile time)
//
// Looks for the function here (in this order)
// ::Level1::Level2::Level3::SendInput()
// ::Level1::Level2::SendInput()
// ::Level1::SendInput()
// ::SendInput()
}
}
}
}
如果你有一个嵌套的名字就更有趣了:
namespace Level1
{
namespace Level2
{
namespace Level3
{
LeftClick()
{
::Test::Action(); // Absolute Path: Function Action()
// in namespace Test
// in global namespace
Test::Action(); // Relative Path: Function Action()
// in namespace Test
// in current namespace path.
//
// It will Look for Test (in this order)
// ::Level1::Level2::Level3::Test
// ::Level1::Level2::Test
// ::Level1::Test
// ::Test
//
// In the first Test (and only the first) it finds it will
// try and resolve the Action() function. If it is not there
// it is a compile time error.
}
}
}
}
强制在全局范围内查找符号。
void foo() {} // 1
namespace A
{
void foo() {} // 2
void bar()
{
foo(); // 2
::foo(); // 1
}
}
以这种方式使用作用域操作符意味着您引用的是全局作用域。
为了节省宝贵的时间和按键,请检查没有作用域的作用域解析操作符。
::
用于直接从对象外部访问对象
相关文章:
- 如何将enable-if与模板参数和参数包一起使用
- 如何将PERF_AMPLE_READ与mmap一起使用
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 控制允许动态运行c++的并发操作数
- 如何将C++中的库和头与MinGW一起使用
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 为什么我不能将 rand() 与数组的大小一起使用?
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 不能将复制初始化与隐式转换的多个步骤一起使用
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 将fold表达式与std::一起用于两个元组
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 将 std::allocate_shared 与多态资源分配器一起使用
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 将 exprtk 与自定义类的对象一起使用
- 将 std::set 与基于键的比较器一起使用
- 将运算符 ^ 与“double”操作数一起使用会发出编译器错误
- C++ 将"-"操作数与 list.back() 一起使用
- 为什么::(作用域)与空左操作数一起使用