C和C++中使用结构体的一点区别


从学校毕业以后,开发东西几乎全部是c++,今天在Linux用c编程,发现关于结构体在定义和使用的上的一点区别。至于结构体在c++有类的特性,这里不做赘述,感兴趣的朋友可以自己查看c++ primer的相关章节。

以前在c++中定义和使用结构体如下:

// definition

typedef struct Student_t

{

  int num;

  char name[128];

}Student, *PStudent;

//or

struct Student_t

{

  int num;

  char name[128];

// usage

Student st;

Student_t st;

上面代码中使用Student或者Student_t直接定义变量,都没有问题。

如果把上述代码搬到纯c环境(用C编译器,如gcc),Student st是没有问题的, 但是Student_t st;则编译出错。c语言要求前面必须加struct关键字。也就是 struct Student_t st;

上述问题与操作系统环境没有关系,只与编译器相关,将上述编译出错的代码用g++编译就没有问题。

相关内容