::是运算符中等级最高的,它分为三种:
1)global scope(全局作用域符),用法(::name)
2)class scope(类作用域符),用法(class::name)
3)namespace scope(命名空间作用域符),用法(namespace::name)
他们都是左关联(left-associativity)
他们的作用都是为了更明确的调用你想要的变量,如在程序中的某一处你想调用全局变量a,那么就写成::a,如果想调用class A中的成员变量a,那么就写成A::a,另外一个如果想调用namespace std中的cout成员,你就写成std::cout(相当于using namespace
std;cout)意思是在这里我想用cout对象是命名空间std中的cout(即就是标准库里边的cout)
比如几天在看一个TCP的网络程序时,程序中自己定义了一个类封装了IP链接,而且名称也是用的connect,具体如下
class IPStack
{
public:
........
........
int connect(const char* hostname, int port)
{
int type = SOCK_STREAM;
struct sockaddr_in address;
int rc = -;
sa_family_t family = AF_INET;
struct addrinfo *result = NULL;
struct addrinfo hints = {, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, , NULL, NULL, NULL};
if ((rc = getaddrinfo(hostname, NULL, &hints, &result)) == )
{
struct addrinfo* res = result;
/* prefer ip4 addresses */
while (res)
{
if (res->ai_family == AF_INET)
{
result = res;
break;
}
res = res->ai_next;
}
if (result->ai_family == AF_INET)
{
address.sin_port = htons(port);
address.sin_family = family = AF_INET;
address.sin_addr = ((struct sockaddr_in*)(result->ai_addr))->sin_addr;
}
else
rc = -;
freeaddrinfo(result);
}
if (rc == )
{
mysock = socket(family, type, );
if (mysock != -)
{
int opt = ;
//if (setsockopt(mysock, SOL_SOCKET, SO_NOSIGPIPE, (void*)&opt, sizeof(opt)) != 0)
// printf("Could not set SO_NOSIGPIPE for socket %d", mysock);
rc = ::connect(mysock, (struct sockaddr*)&address, sizeof(address)); //调用全局的connect函数即socket.h里面的connect函数
}
}
return rc;
}
::的用法算是C++中的基础,如果运用的好的话,你程序的出错率也许会降很多