C++基础——记一次双冒号(::)的使用
前言
最近在阅读mediasoup源码中发现了以下的一个用法:
// 此处的::对命名空间外的同名类进行调用
ConsumerSocket::ConsumerSocket(int fd, size_t bufferSize, Listener* listener)
: ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::CONSUMER), listener(listener)
{
MS_TRACE_STD();
}
我们都知道,当父类初始化需要传参时,子类的构造函数必须显示的初始化父类的构造函数。否则会提示以下编译错误:
Constructor for ‘son’ must explicitly initialize the base class ‘father’ which does not have a default constructor
而这里的使用则让人产生了较大的误会。这是因为在Channel这个命名空间和全局空间里有两个同名类,而为了这几个类之间能相互传递内容,则出现了各类奇怪的继承。下面我模拟一下这个情况:
# main.cpp
#include <iostream>
#include "father.h"
namespace test {
class father {
public:
father(int a){
std::cout << "father" << a << std::endl;
}
};
class son : public ::father {
public:
son(int b);
};
son::son(int b): ::father(b) {
std::cout << "son" << b << std::endl;
}
}
int main() {
std::cout << "Hello, World!" << std::endl;
test::son s(1);
return 0;
}
# father.h
#include <iostream>
#ifndef TEST__FATHER_H
#define TEST__FATHER_H
class father {
public:
father(int a) {
std::cout << " father other" << a << std::endl;
}
};
namespace test2 {
class father {
public:
father(int a) {
std::cout << " father test2" << a << std::endl;
}
};
}
#endif //TEST__FATHER_H
上述代码中存在两个同名的类father。而为了继承test外部的类必须使用::来表示使用域外全局域,因此继承和构造函数中初始化都需要使用::。