C++ Using 用法

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成员。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值