【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)如果一个类只在模块内部使用,则可以实现类名隐藏。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值