函数调用前面的 :: 是什么意思?

use*_*926 1 c++

I2CDevice::I2CDevice(unsigned int bus, unsigned int device) {
    this->file=-1;
    this->bus = bus;
    this->device = device;
    this->open();
}

int I2CDevice::open(){
   string name;
   if(this->bus==0) name = BBB_I2C_0;
   else name = BBB_I2C_1;

   if((this->file=::open(name.c_str(), O_RDWR)) < 0){
      perror("I2C: failed to open the bus\n");
      return 1;
   }

   if(ioctl(this->file, I2C_SLAVE, this->device) < 0){
      perror("I2C: Failed to connect to the device\n");
      return 1;
   }

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面是做Linux I2C接口的部分代码,我的问题是:

this->file=::open(name.c_str(), O_RDWR)
Run Code Online (Sandbox Code Playgroud)

我认为这是尝试使用 open() 函数为文件描述符 this->file 分配一个值。但为什么会有一个“::”符号呢?为什么不只是“open()”。

Zan*_*ynx 5

这就是 C++ 名称解析。运算::符分隔命名空间。当它开始一个名称时,它是对顶级全局名称空间的显式引用。它在这里的使用保证了它引用的是openC 库声明的函数,而不是open恰好在类、当前命名空间或任何using namespace声明中的任何函数。

在此特定示例中,::open是必需的,因为它位于open类函数内部。简单地调用这里会导致名称解析错误,因为类中open有一个但没有匹配的覆盖。open如果参数确实匹配,那么这将是一个递归调用,这不是您想要的。