struct Stt
{
int num1;
int num2;
};
1. 实例化的不同
C:
1.struct Stt ex;
2. 使用
typedef struct Stt
{
int num1;
int num2;
}St;
可以直接 St stt;
C++:
1.struct Stt ex;
2.Stt ex;
3.需要注意的是
struct Student
{
int no;
char name[12];
}stu1;
等价于Student stu1;而非起了一个别名
2. tips
另查阅资料知,某些C++标准中是把struct当作类来处理的,隐藏的构造函数可能具有private属性。目前还没遇到过这类问题,先做此tips以便查阅。
3.一些常用的用法
在写链表的时候常常会有一些约定俗成的写法
typedef struct QNode
{
QElemType data; //数据域
struct QNode *next; //指针域
}QNode,*QueuePtr;
QNode就是结构体QNode的别名,
*QueuePtr 是一个结构体指针,相当于 int的 int *
意思是 QueuePtr ptr 等价于 QNode * ptr;
4. 如果加一个数组呢?
简而言之,
-
有typedef
arr[i] 是一个“别名”。 -
没有typedef
arr[i] 真的是一个数组。
以上所有,都在下面这个demo里了 需要自取
#include <iostream>
#include <Windows.h>
#include <sstream>
#include <vector>
#include <set>
#include <list>
#include <string>
using namespace std;
template<class T>
void tra(T t1)
{
for(auto i:t1)
{
cout<<i;
}
cout<<endl;
}
typedef struct Stu
{
int age;
string name;
}Stu,*pstu,Arr[10];
struct Stu2
{
int age;
string name;
}arr2[10];
void myp(Stu s)
{
cout<<s.name<<" : "<<s.age<<endl;
}
void myp(Stu *s)
{
cout<<s->name<<" : "<<s->age<<endl;
}
int main()
{
Stu s1;
s1.name="s1";s1.age=18;
myp(s1);
pstu s2;
s2=(pstu)malloc(sizeof(struct Stu));
s2->name="s2";
s2->age=20;
myp(s2);
Stu *s3;
s3=(struct Stu*)malloc(sizeof(struct Stu));
s3->name="s3";
s3->age=23;
myp(s3);
Arr arr;
string str;
stringstream ss;
for(int i=0;i<10;i++)
{
//to_string在该编译器下报错
ss<<i;
ss>>str;
ss.clear();
arr[i].name=str;
arr[i].age=i;
myp(arr[i]);
}
cout<<"There is no \"Typedef\":"<<endl;
for(int i=0;i<10;++i)
{
arr2[i].name=str;
arr2[i].age=i;
myp(arr[i]);
}
}