【C++】内部类(解决名字冲突问题一)

将内部类看成普通成员,符合普通成员的规则,用法就是正常类的使用方法。

定义内部类

把一个类的定义写在另一个类的内部,则成里面的这个类为内部类。例如,下面代码中的Inner类

#include <stdio.h>
#include <string.h>

class Test
{
public:
    class Inner
    {
    public:
        char name[64];
    };
};

int main()
{
    Test::Inner a;
    strcpy(a.name, "nick");
    printf("name:%s \n", a.name);
    return 0;
}

注意:内部类和外部类互相没有特权

他们不是朋友关系;

他们不是父子关系;

他们没有任何特殊关系。

比如下面这个例子,被声明为私有变量后就不能被访问:

class Test
{
public:
	class Inner
	{
	public:
		int id;
		char name[64];
	private:
		void Print()
		{
			printf("Inner testing ... \n");
		}
	};
public:
	Test()
	{
		Inner i;
		i.Print();
	}
};

头源分离

main.cpp

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include "Test.h"

int main()
{
	Test::Inner a;
	strcpy(a.name, "nick");
	printf("name:%s \n", a.name);
	a.Print();
	return 0;
}

Test.h

#pragma once
class Test
{
public:
	Test();
	~Test();
public:
	class Inner
	{
	public:
		int id;
		char name[64];
	public:
		void Print();
	};
};

Test.cpp

#include "stdafx.h"
#include "Test.h"


Test::Test()
{
}


Test::~Test()
{
}

void Test::Inner::Print()
{
	printf("Inner testing ... \n");
}

看完了内部类的用法,发现他与普通类没有任何区别,那为什么需要内部类?

(1)避免命名重复;

(2)如果一个类只在模块内部使用,则可以实现类名隐藏。

猜你喜欢

转载自blog.csdn.net/u013066730/article/details/84616441