结构、联合、枚举的区别
结构、联合的区别:
1、在C++中定义结构、联合对象时,struct、union关键字可以省略(也就不需要使用typedef进行类型重定义)。
2、在C++中结构、联合的内部,可以有成员函数,使用结构、联合对象加.或->调用,成员函数的内部可以直接使用成员变量,成员函数可以自动区别对象的成员变量。
3、在C++中结构、联合中可以对成员变量、成员函数进行访问权限的管理:
private 私有的成员
public 公开的成员
protected 受保护的成员
4、在C++中创建、销毁结构、联合对象时,会自动调用构造函数(以结构名命名)、析构函数(~结构名命名)。
#include <iostream>
using namespace std;
struct Student
{
int id;
char name[20];
short age;
void show(void)
{
cout << id << " " << name << " " << age << endl;
}
Student(void)
{
cout << "我是构造函数" << endl;
}
~Student(void)
{
cout << "我是析构函数" << endl;
}
};
union Data
{
char ch;
int num;
};
int main(int argc,const char* argv[])
{
/*
Student stu1 = {10010,"hehe",28};
Student stu2 = {10011,"xixi",30};
stu1.show();
stu2.show();
*/
Student stu;
Data d;
return 0;
}
枚举:
1、定义枚举变量时,enum关键字可以省略。
2、C++中的枚举不再是int类型模拟的,整数不能给枚举变量赋值。
#include <iostream>
using namespace std;
enum DirectionKey
{
Up,Down,Right,Left
};
int main(int argc,const char* argv[])
{
DirectionKey key;
// key = 1234;
key = Down;
cout << key << endl;
return 0;
}
630

被折叠的 条评论
为什么被折叠?



