chromium - using special class

前言

在web-ui中post一个任务时,使用到了BrowserThread::PostTask。
开始编译不过,去看官方测试程序时,发现人家用了using content::BrowserThread;
我以前只用using namesapce xx.
看来工程大了,作者考虑的就是不同。
指定某个实现文件使用特定名字空间的类,看起来更明确。
做了实验,在同一个cpp中的不同函数中,也可以指定使用不同空间的相同类名。

实验

// @file main.cpp
// @brief test using special class
// @note
// 如果不在函数中指定用哪个名字空间的哪个类, 可以在实现文件的上面声明使用哪个空间的哪个类
// 如果工程比较大,有很多同名的类,使用using ns:class 比用 using namespace好, 使用名字空间中的类的粒度更细.
// 查代码实现时,更明确,代码维护更方便。

#include <iostream>

namespace ns_a {
	class cls_a
	{
	public:
		cls_a() :m_i_cnt(0) {}

		cls_a(int i_in) {
			m_i_cnt = i_in;
		}

		cls_a& operator=(const cls_a& in) = delete;

		cls_a(double f_in) = delete;

		void show() {
			printf("ns_a::cls_a m_i_cnt = %d = 0x%X\n", m_i_cnt, m_i_cnt);
		}

	private:
		int m_i_cnt;
	};
}

namespace ns_b {
	class cls_a
	{
	public:
		cls_a() :m_i_cnt(0) {}

		cls_a(int i_in) {
			m_i_cnt = i_in;
		}

		cls_a& operator=(const cls_a& in) = delete;

		cls_a(double f_in) = delete;

		void show() {
			printf("ns_b::cls_a m_i_cnt = %d = 0x%X\n", m_i_cnt, m_i_cnt);
		}

	private:
		int m_i_cnt;
	};
}

using ns_a::cls_a;

void test_ns_a();
void test_ns_b();
void test_ns_default();

int main()
{
	test_ns_a();
	test_ns_b();
	test_ns_default();
	return EXIT_SUCCESS;
}

/** run result
>> test_ns_a()
ns_a::cls_a m_i_cnt = 0 = 0x0
>> test_ns_b()
ns_b::cls_a m_i_cnt = 1024 = 0x400
>> test_ns_default()
ns_a::cls_a m_i_cnt = 666 = 0x29A
*/

void test_ns_a()
{
	using ns_a::cls_a;

	printf(">> test_ns_a()\n");
	cls_a a;
	a.show();
}

void test_ns_b()
{
	using ns_b::cls_a;

	printf(">> test_ns_b()\n");
	cls_a b(1024);
	b.show();
}

void test_ns_default()
{
	printf(">> test_ns_default()\n");
	cls_a a(666);
	a.show();
}

猜你喜欢

转载自blog.csdn.net/LostSpeed/article/details/85091096