> 文章列表 > C ++ 基础入门。加强变量、指针、结构体理解

C ++ 基础入门。加强变量、指针、结构体理解

C ++ 基础入门。加强变量、指针、结构体理解

1、

const放外面,值不可以改。只读
C ++ 基础入门。加强变量、指针、结构体理解
同理于指针
看const右侧紧跟着的是指针还是常量, 是指针就是常量指针,是常量就是指针常量
const 放外面,值不可以改
C ++ 基础入门。加强变量、指针、结构体理解

2、

所有的指针类型,包括结构体指针
double * int *都是和操作系统位数一致,原理是因为你要表示所有的地址空间大小。
比如:32位操作系统为4个字节

3、

从存储空间大小的角度重新审视。隐含着空间的大小。比如,数组里面,一个int是四个字节,在存储空间里面连续存储。
如果指针的数据类型和指向的内存空间对应不上的话,会报错。所以严格要求在定义指针的时候数据类型要和指向的变量相对应。
p ++;隐含着是加一次几个字节。

64位编译器
char :1个字节
char*(即指针变量): 8个字节
short int : 2个字节
int: 4个字节
unsigned int : 4个字节
float: 4个字节
double: 8个字节
long: 8个字节
long long: 8个字节
unsigned long: 8个字节

	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };int * p = arr;  //指向数组的指针for (int i = 0; i < 10; i++){//利用指针遍历数组cout << *p << endl;p++;}

4、
放在函数()里的值,本质上和单独设置一个没什么区别
值传递:不会改变实参的值
地址传递:会改变实参的值
引用传递:重命名

下面两种没有区别。对应的物理申请空间都是图1

#include <iostream>
using namespace std;void test(int j)
{j=20;cout<<"j="<<j<<endl;
}void main()
{int i=10;test(i);cout<<"i="<<i<<endl;system("pause");
}
#include <iostream>
using namespace std;void main()
{int i=10;int j=i;j=20;cout<<"i="<<i<<endl;cout<<"j="<<j<<endl;system("pause");
}

C ++ 基础入门。加强变量、指针、结构体理解


下面两种没有区别

#include <iostream>
using namespace std;void main()
{int i=10;int *j=&i;*j=20;cout<<"i="<<i<<endl;cout<<"j="<<*j<<endl;system("pause");
}
#include <iostream>
using namespace std;void test(int* j)
{* j = 20;cout << "j=" << *j << endl;
}int main()
{int i = 10;test(&i);cout << "i=" << i << endl;system("pause");
}

C ++ 基础入门。加强变量、指针、结构体理解


下面两种没有区别

#include <iostream>
using namespace std;int main()
{int i=10;int &j=i;j=20;cout<<"i="<<i<<endl;cout<<"j="<<j<<endl;system("pause");
}
#include <iostream>
using namespace std;void test(int& j)
{j = 20;cout << "j=" << j << endl;
}
int main()
{int i = 10;test(i);cout << "i=" << i << endl;system("pause");
}

C ++ 基础入门。加强变量、指针、结构体理解


5、
结构体变量,通过.来访问成员
结构体指针通过->来操作结构体成员

#include <iostream>
using namespace std;struct Node {string name;int age;int score;
};int main()
{struct Node a = { "su", 10, 100 };struct Node* p;p = &a;p->score = 80;cout << p->name << ' ' << p->age << ' ' << p->score << endl;system("pause");return 0;
}

6、
同理有值传递void printStudent(student stu )
和地址传递void printStudent2(student *stu)
注意
值传递和地址传递的区别在于,值传递要进行拷贝,如果传入的参数是一个成千上万的结构体数组,那么也要在内存中拷贝一个一模一样的,所以会有拷贝数据的内存消耗。但是结构体指针大小恒为4个字节,这就是指针的好处。
除此之外,可以用const student *stu来实现只读的效果,防止失误进行写操作(一旦有修改的操作就会报错)。
(在最前面加const值不能变)