结构体类型的Qvector容器:首先是结构体的说明


结构体类型的Qvector容器:首先是结构体的说明
在c语言中
1 首先:
在C中定义一个结构体类型要用typedef:
typedef struct Student
{
int a;
}Stu;// Stu只是类型,只有通过变量才能访问结构体中的数据
于是在声明变量的时候就可:Stu stu1;// stu1是变量
如果没有typedef就必须用struct Student stu1;来声明
这里的Stu实际上就是struct Student的别名。
另外这里也可以不写Student(于是也不能struct Student stu1;了)
typedef struct
{
int a;
}Stu;
但在c++里很简单,直接
struct Student// 结构体类型
{
int a;
};// 如果在后面加stu的话stu是变量
于是就定义了结构体类型Student,声明变量时直接Student stu2;
===========================================
2其次:
在c++中如果用typedef的话,又会造成区别:
struct Student
{
int a;
}stu1;// stu1是一个变量
typedef struct Student2
{
int a;
}stu2;// stu2是一个结构体类型
使用时可以直接访问stu1.a
但是stu2则必须先 stu2 s2;
然后 s2.a=10;

然后定义结构体类型的qvector容器:两种方式
struct Student
{
    int age;
    QString name;
};// 这里不给他声明变量名

第一种(以c++为例):
QVector <Student>stu;//这是在.h中声明的
后面用容器的话写个循环。
for(int i = 0;i<stu.size();i++)
{
    cout<< stu.at(i).age;
    cout<<stu.at(i).name;
}
添加容器的话
Student student1 = {20,“小明”};
Student student2 = {20,“小红”};
stu.push_back(student1);
stu.push_back(student2);

第二种(以c++为例):
QVector <Student *>stu;//这是在.h中声明的
同样的用到也是写个循环
for(int i = 0;i<stu.size();i++)
{
    cout<< stu.at(i)->age;
    cout<<stu.at(i)->name;
}   
添加容器的话   
可以直接生成一个结构体的指针;
Student *student = new Student;
student->age = 20;
student->name = QString::fromLocal8Bit("小明");
stu.push_back(student);

猜你喜欢

转载自blog.csdn.net/qq_36583051/article/details/78804652