c++的结构、联合、枚举

结构、联合、枚举的区别

结构、联合的区别:

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;
}
  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值