C++ 中using的常见用法 :
(1)引入命名空间namespace;
(2)指定别名;
(3)在派生类中引用基类的成员。
引入命名空间namespace
常见的引入std:
using namespace std;
引入命名空间里的成员
using std::string
using std::cout
对于引入命名空间在工程上可以有更好的方式。如果像之前一样在include之后就用using引入命名空间这样并不一定好,更好的方法是在一个范围内引入该范围内所需的命名空间里的成员,比如就在一个class里才引入。不过请注意,这是C++20才有的新特性。
enum class Color { red, green, blue };
class MyClass {
using Color::red;
Color c = red; // This is OK from C++20
};
指定别名
很容易的用法:
using a = b;
a就是b的一个别名。
在读Apollo自动驾驶代码中,为了在代码中更简洁地用Eigen库中的MatrixXd方法,而不是每次都要写上类名。但是注意在所使用的文件内不要和其他变量名有冲突。
using Matrix = Eigen::MatrixXd;
在派生类中引用基类的成员
例如下面的例子派生类从基类引入sum()方法:
#include <iostream>
using namespace std;
class Base {
public:
void sum(int a, int b) {
cout << "Sum: " << a + b << endl;;
}
};
class Derived : protected Base {
public:
using Base::sum;
};
int main() {
Derived D;
// Due to protected inheritance, all the public methods
// of the base class become protected methods of the
// derived class. If the using keyword word was not used,
// calling sum like this would not have been possible.
D.sum(10, 20);
return 0;
}
由于是protected继承,所以需要使用using进行方法的引用,否则派生类无法使用基类的public成员。