c++11 using的三种用法

前言

前段时间,正巧碰到了UE4源码中的一些代码中using的用法,因此查阅资料之后写下了这篇文章

 实例代码:

#include <iostream>
using namespace std;

namespace TestNameSpace
{
	void TestFunction() 
	{
		cout << "这是命名空间的TestFunction" << endl;
	}
}

class Parent
{
public:
	Parent() {};
	~Parent() {};
	int value = 10;
	void TestFunction()
	{
		cout << "这是父类的TestFunction"<<endl;
	}
};

class Child:private Parent
{
public:
	Child() {};
	~Child() {};
	using Parent::TestFunction;
	using test = int;
	using Parent::value;
};

int main()
{
	Child a;
	using namespace TestNameSpace;
	TestFunction();
	a.TestFunction();
	a.value = 20;

	cout << "a.value"<< 20 << endl;
	return 0;
}

运行结果:

上面是我对using三种用法的尝试

用法一:就是c++98常见的导入命名空间,则可以使用命名空间中的方法,在此不过多赘述,想必大家都已经掌握,列如示例中using namespace TestNameSpace;使用之后则可以直接调用TestNameSpace命名空间中的内容。

用法二:起别名,这通常用于模板函数作起别名的作用,类似于Typedef,但是区别在于用usin的方式,可以私有继承,但是却能在main函数中访问,例如示例中class Child:private Parentprivate继承的,但是在main函数中却访问到Child::value变量,开局第一张图则是起别名的作用

用法三:就是在子类中引用基类的成员,using Parent::TestFunction;using Parent::value;在此处可以访问到私有继承的方法

猜你喜欢

转载自blog.csdn.net/weixin_56946623/article/details/126990080
今日推荐