C/C++结构体定义

在C语言和C++中,结构体定义是存在区别的,好比在C语言中定义结构体,首先是使用typedef。
ios

typedef struct Student{
    int age;
}Stu;

此时定义的结构体。可使用 struct Student stu1 来声明变量。固然也可使用Stu stu1 来声明,由于此时已经将struct Student 定义为Stu。spa

#include <stdio.h>
typedef struct Student{
	int a;
}Stu;
int main()
{
  	 struct Student stu1;
  	 stu1.a = 17;
  	 printf("第一个:%d\n", stu1.a);
  	 Stu stu2;
  	 stu2.a = 18;
     printf("第二个:%d\n", stu2.a);
     return 0;
}

而此时C++ 只须要定义 struct Student就能够了
io

#include <iostream>
using namespace std;
struct Student{
    int a;
}stu2;  //声明结构体的同时声明变量
int main() {
    struct Student stu1;
    stu1.a = 18;
    stu2.a = 19;
	cout  << "第一个:"<< stu1.a<<endl;
	cout  << "第二个:"<< stu2.a<<endl;
	return 0;
}

声明的同时能够直接声明一个变量,好比stu2。而在后续的声明中,能够直接使用 struct Student 来声明新的变量。若是不声明这个结构体的名称,则没法声明对于的变量,此处就不能声明stu1class

#include <iostream>
using namespace std;
struct {
    int a;
}stu2;  //声明结构体的同时声明变量
int main() {
    //struct Student stu1;
    //stu1.a = 18;
    stu2.a = 19;
	//cout  << "第一个:"<< stu1.a<<endl;
	cout  << "第二个:"<< stu2.a<<endl;
	return 0;
}

未完待续
stream

相关文章
相关标签/搜索