文章目录

没有用​​typedef​​时候


C语言


#include <stdio.h>

struct Books {
int sal;
int id;
};

int main() {
struct Books book; // 声明一个叫做book的结构体
book.sal = 10;
book.id = 10010;
printf("%d %d", book.sal, book.id);
return 0;
}


C++


#include <iostream>

using namespace std;

struct Books {
int sal;
int id;
}book;

int main() {
book.sal = 10;
book.id = 10010;
cout << book.sal << ' ' << book.id << endl;
return 0;
}

有用​​typedef​​时候


C语言


#include <stdio.h>

typedef struct {
int sal;
int id;
}books;

int main() {
books book;
book.sal = 10;
book.id = 10010;
printf("%d %d", book.sal, book.id);
return 0;
}


C++


#include <iostream>

using namespace std;

typedef struct {
int sal;
int id;
}Books;

int main() {
Books book;
book.sal = 10;
book.id = 10010;
cout << book.sal << ' ' << book.id << endl;
return 0;
}

小结

  1. C结构体在定义时除非使用typedef,否则之后定义变量都必须跟上struct + 结构体名,而C++结构体可以直接使用结构体名,不受限制。
  2. C结构体不能在结构体中初始化成员变量,而C++结构体可以。
  3. C结构体的空结构体sizeof为0,C++的sizeof为1。