[C++基础]结构体和类


一些基础知识点,结构体和类理论

基础知识点

主函数:

应用程序入口
一个项目只能有一个主函数

主函数形式

1:int main()c++标准形式

2:int main(void) c标准形式

3:int main(int argc,char* argv[ ]) 命令行参数

4:main() c

5:void main() (不提倡)

输出 输入

cout可以连续输出,自动识别类型

<<’a’<<21<<”dddd”

“” 字符串

‘’字符

小数自动识别成double,所以定义浮点数时,要在最后加f

float b=12.122f

endl

换行,并且清空刷新缓冲区

\n换行符依旧可以用

c结构体

结构体中不能直接有函数成员,但可以通过一定的语法间接调用函数,比如函数指针
声明结构体变量必须有struct关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
typedef struct Node
{
int m;
void(*p)();//函数指针
};
void fun()
{
printf("hello");
}

int main(void)
{
struct Node a = { 1,fun };
a.p();//调用函数

return 0;
};

在C中定义一个结构体类型要用typedef:

1
2
3
4
typedef struct Student
{
int a;
}Stu;

于是在声明变量的时候就可:Stu stu1;(如果没有typedef就必须用struct Student stu1;来声明)

这里的Stu实际上就是struct Student的别名。Stu==struct Student

1
2
3
4
typedef struct
{
int a;
}Stu;

另外这里也可以不写Student(于是也不能struct Student stu1;了,必须是Stu stu1;)

c++ 结构体

在c++中如果用typedef的话,又会造成区别:

1
2
3
4
struct   Student
{   
int   a;   
}stu1;//stu1是一个变量

1
2
3
4
typedef   struct   Student2   
{   
int   a;   
}stu2;//stu2是一个结构体类型=struct Studen

声明变量不用struct

可以放函数成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
struct Node
{
int m;
void fun()
{
printf("hello");
}
};


int main()
{
Node a;
a.fun();
system("pause");

return 0;


};