What does prepending “::” to a function call do in C++?
Possible Duplicate:
What is the meaning of prepended double colon “::” to class name?
我一直在看一个遗留的C++代码,它有这样的事情:
1 2 | ::putenv(local_tz_char); ::tzset(); |
在函数调用前加"::"的语法是什么意思?谷歌福让我失望了。
这意味着编译器将在全局命名空间中查找函数
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; //global function void foo() { cout <<"This function will be called by bar()"; } namespace lorem { void foo() { cout <<"This function will not be called by bar()"; } void bar() { ::foo(); } } int main() { lorem::bar(); //will print"This function will be called by bar()" return 0; } |
也称为范围解析运算符
In C++ is used to define the already declared member functions (in the
header file with the .hpp or the .h extension) of a particular class.
In the .cpp file one can define the usual global functions or the
member functions of the class. To differentiate between the normal
functions and the member functions of the class, one needs to use the
scope resolution operator (::) in between the class name and the
member function name i.e. ship::foo() where ship is a class and foo()
is a member function of the class ship.
维基百科的例子:
1 2 3 4 5 6 7 8 9 10 11 12 | #include <iostream> // Without this using statement cout below would need to be std::cout using namespace std; int n = 12; // A global variable int main() { int n = 13; // A local variable cout << ::n << endl; // Print the global variable: 12 cout << n << endl; // Print the local variable: 13 } |
昨天(+1年)有一个关于类似问题的讨论。也许你可以在这里找到一个更深入的答案。
预填的双冒号":"的意思是什么?
它意味着:在全局命名空间中查找函数。
它将使用特定的非限定名称(而不是使用
例如,如果您有一个带有局部变量
1 2 3 4 5 6 7 | int var = 0; void test() { int var = 5; cout <<"Local:" << var << endl; cout <<"Global:" << ::var << endl; } |
IBM C++编译器文档使它像这样(源代码):
The :: (scope resolution) operator is used to qualify hidden names so
that you can still use them. You can use the unary scope operator if a
namespace scope or global scope name is hidden by an explicit
declaration of the same name in a block or class.
对于类内部的方法和外部相同名称的版本也可以这样做。如果要访问特定命名空间中的变量、函数或类,可以这样访问它:
但有一点需要注意,即使它是一个运算符,也不是可以重载的运算符之一。