C++-结构体(struct),联合(union),枚举(enum)

使用struct定义结构体,使用Teacher t = {"", "", ""} 进行初始化操作

/*
结构体
*/ 
#include <iostream>
using namespace std; 

struct Teacher{
    char name[20]; 
    int  age; 
    double salary; 
    void who(void) {    
        cout << "名字是" << name << ",年龄是" << age << 
",工资是" << salary << endl;  
    }
};

int main() {
    Teacher t = {"王自新", 20, 20000}; //结构体初始化 
    t.who(); 
}

union联合体

/*
union联合保存
*/ 
#include <iostream>
#include <cstdio>
using namespace std; 

int main() {
    union {
        unsigned int s1; 
        unsigned char s2[4]; 
    };
    s1 = 0x12345678; 
    for (int i = 0;i < 4;i++) {
        printf("0x%x ", s2[i]); 
    }
    printf("\n"); 
    return 0; 
    


}

enum枚举

/*
枚举
*/
#include <iostream>

using namespace std; 
int main() {

    enum Color {RED, YELLO, BLUE}; 
    cout << RED << "," << YELLO << "," << BLUE << endl;
    Color c; //获取到第一个数字 
    cout << c << endl;  
    
}

 

posted @ 2020-03-30 10:56  c语言我的最爱  阅读(372)  评论(0编辑  收藏  举报