使用::作用域运算符,可以让你的代码减少出错的概率。今天在读空间配置器接口时,看到了如下代码。
template <class T>
inline T* _allocate(ptrdiff_t size, T*){
set_new_handler(0);
T* tmp = (T*)(::opterator new(size_t)(size * sizeof(T)));
if (tmp == 0){
cerr << "out of memory" << endl;
exit(1);
}
return tmp;
}
此处,::operator new中::的作用是调用了全局的operator new()函数。::作用域运算符,主要有以下三个使用场景。
全局作用域符
像上述代码的形式一样,全局作用域运算符使用(::valName)的形式来调用全局函数或者全局变量。当我们在类或者函数外定义了同名函数或者变量。我们可以使用::来调用全局函数。下面的例子是在类中重载operator new函数,并在重载函数中调用全局的operator new函数。(注:new和delete操作我们是无法改变的,我们只能重载operator new函数)
class allocator{
pulic:
allocator() {cout << "construct" << endl;}
~allocator() {cout << "destruct" << endl;}
void* operator new(size_t size){
printf("malloc size of %d \r\n", size);
return ::operator new(size);
}
void operator delete(void *ptr){
printf("free the memory");
::operator delete(ptr);
}
}
命名空间作用域符
可以使用(namespace::valName)的形式来声明调用哪一个命名空间的变量名,从而避免重名函数或者变量。
//allocator.h
namespace newAllocator{
class allocator{
/*
* balabala
*/
}
}
//allocator.cpp
#include "allocator.h"
#include <iostream>
using namespace std;
int main(){
int a[5] = {0, 1, 2, 3, 4};
vector<int, newAllocator::allocator> v(a, a+5);
}
上述代码,我们使用了newAllocator::allocator来指明使用newAllocator命名空间下的allocator类。
类作用域符
在类中声明函数后,可以在类外使用域作用符来完成函数定义。使用形式为(class::funName)
class allocator{
public:
void foo();
}
void allocator::foo(){
cout << "this is foo" << endl;
}