嵌套类型
嵌套类型,nested type,定义于外围类(outer class)作用域内的类型
class CAnimal
{
private:
//Group mGroup;
private:
//EFood food;
private:
typedef int Group;
protected:
enum EFood
{
RICE = 0,
MEAT = 1,
FISH = 2,
FRUIT = 3,
};
private:
Group mGroup;
private:
EFood food;
};
class CDog : public CAnimal
{
private:
//Group mGroup;
private:
EFood food;
};
总结:
- 嵌套类型是独立类型,与外围类无任何逻辑上关联,仅寄存于外围类作用域而已
- 嵌套类型受外围类访问权限控制,遵守外围类对象成员同样访问权限规则,可把嵌套类型理解为外围类类型成员
- 嵌套类型必须遵守先定义后使用规则,即嵌套类型被外围类使用之前必须前置定义
嵌套类
嵌套类,nested class,特殊嵌套类型,其类型为class
class CAnimal
{
public:
CAnimal() { cout << "CAnimal()" << endl; }
public:
void info() { cout << "CAnimal::info()" << endl; }
public:
//void feed(CFood food);
public:
class CGroup
{
public:
CGroup() { cout << "CGroup()" << endl; }
public:
void info() { cout << "CGroup::info()" << endl; }
public:
int mGId;
private:
//CFood food;
};
public:
class CFood
{
public:
CFood() { cout << "CFood()" << endl; }
public:
void info() { cout << "CFood::info()" << endl; }
public:
void feed(CAnimal animal);
public:
int mFId;
public:
CGroup mGroup;
};
public:
void feed(CFood food);
public:
int mCId;
public:
CGroup mGroup;
};
void CAnimal::feed(CAnimal::CFood food)
{
cout << "CAnimal::feed(CAnimal::CFood)" << endl;
food.mFId = 0;
food.info();
food.mGroup.mGId = 0;
food.mGroup.info();
}
void CAnimal::CFood::feed(CAnimal animal)
{
cout << "CAnimal::CFood::feed(CAnimal)" << endl;
animal.mCId = 0;
animal.info();
animal.mGroup.mGId = 0;
animal.mGroup.info();
}
void nested_class()
{
CAnimal animal;
CAnimal::CFood food;
animal.feed(food);
food.feed(animal);
}
总结:
- 嵌套类是特殊嵌套类型,因此嵌套类遵守嵌套类型一切规则
- 嵌套类可访问外围类一切成员(对象成员&类型成员),只要访问权限允许
- 外围类可访问嵌套类一切成员(对象成员&类型成员),只要访问权限允许
- 嵌套类可访问嵌套类一切成员(对象成员&类型成员),只要访问权限允许
局部类型
局部类型,local type,顾名思义定义于局部作用域内,而局部作用域存在于函数内,因此局部类型定义于函数内,该函数即为局部类型外围函数
void local_type()
{
typedef int Group;
enum EFood
{
RICE = 0,
MEAT = 1,
FISH = 2,
FRUIT = 3,
};
Group group;
EFood food;
group = 0;
food = RICE;
}
总结:
- 局部类型只能被外围函数使用
- 局部类型必须遵守先定义后使用规则,即局部类型被外围函数使用之前必须前置定义
局部类
局部类,local class,特殊局部类型,其类型为class
void local_class()
{
int i = 0;
static int si = 0;
enum EFood
{
RICE = 0,
MEAT = 1,
FISH = 2,
FRUIT = 3,
};
class CGroup
{
public:
CGroup() { cout << "CGroup()" << endl; }
public:
void info() { cout << "CGroup::info()" << endl; }
public:
int mGId;
private:
//CFood food;
};
class CFood
{
public:
CFood() { cout << "CFood()" << endl; }
public:
void info() { cout << "CFood::info()" << endl; }
public:
void access()
{
//i = 5;
si = 5;
mFId = RICE;
}
public:
int mFId;
public:
CGroup mGroup;
private:
//static int mTotalFood;
static int getTotalFood() { return 4; }
};
//void CFood::info() { cout << "CFood::info()" << endl; }
}
总结:
- 局部类是特殊局部类型,因此局部类遵守局部类型一切规则
- 局部类不支持使用类作用域操作符,因此局部类函数成员实现只能置于局部类内,不能置于局部类外,局部类不允许声明static数据成员(需使用类作用域操作符在局部类外定义),允许定义static函数成员(无this参数,实现可置于局部类内)
- c++不支持函数嵌套及闭包,因此局部类成员函数不能访问外围函数非static局部对象(外围函数执行结束就释放),允许访问外围函数static局部对象(static局部对象存在于全局数据区,只是寄存于外围函数作用域,外围函数执行结束不释放)