一、类的嵌套:
在定义一个类时, 在其类体中又包含了一个类的完整定义,称为类的嵌套 。类是允许嵌套定义的 。
例1:
#include <iostream>
using namespace std;
class CA //类是允许嵌套定义的
{
class CB //类CB包含在类CA当中,为嵌套定义
{
int i, j;
public:
void set_ij_func(int m,int n)
{
i = m;
j = n;
}
};
float x, y;
public:
CB cb1, cb2; //嵌套类的对象
void set_xy_func(float a, float b)
{
x = a;
y = b;
}
void printfunc()
{
cout << " x=" << x << endl;
cout << " y=" << y << endl;
}
};
例2:
#include <iostream>
using namespace std;
class CC1
{
public:
int x;
void func(); //类体内函数声明
class CC2 //类CC2定义在类CC1体内
{
public:
int y;
void func();//类体内函数声明
}obc; //定义类的对象
};
void CC1::func()//在类体外 函数定义的,函数名前要+类名+::域包含符
{
x = 3000;
cout << " x= " << x << endl;
}
void CC1::CC2::func()//函数定义 在类体外
{
y = 40000;
cout << " y= " << y << endl;
}
int main()
{
CC1 obj;
obj.func(); //此处是调用CC1::func()函数
obj.obc.func(); //此处是调用 CC1::CC2::func()函数
return 0;
}
输出结果:
二、类的对象引用私有数据成员
1)通过公有成员函数为私有数据成员赋值
<