江
江小南
V1
2023/01/11阅读:33主题:萌绿
【C语言】C++引用和C++布尔类型
阅读本文,需要对C语言的基础知识有所了解。C语言基础,我给大家准备了详细的学习资料,微信公众号主页回复“C语言”即可领取。
引言
C++是一种计算机高级程序设计语言,由C语言扩展升级而产生。C++引用能够使编码更加方便快捷。这里也只讲C++的引用,为后面算法做铺垫。
我们通过普通变量和指针变量两种传递来说明。
1. C++的引用
普通变量的传递
C++引用能够使编码更加方便快捷。
C语言代码:
#include <stdio.h>
void modify_num(int *b){ // 使用指针变量接收参数
*b=*b+1;
}
int main() {
int a=10;
modify_num(&a); // &获取地址
printf("after modify_num a=%d\n",a);
return 0;
}
C++代码:
#include <stdio.h>
void modift_num(int &b){
b=b+1;
}
int main() {
int a=10;
modift_num(a);
printf("after modift_num a=%d\n",a);
return 0;
}
以上两种编码,结果均为:
F:\Computer\Project\practice\8\8.3-c++_code\cmake-build-debug\8_3_c___code.exe
after modift_num a=11
进程已结束,退出代码为 0
分析:
我们知道,C语言的函数调用均为值传递。如果对于变量的修改等操作,需要传递变量的地址。而被调用的函数需要使用指针变量进行接收。如果使用C++引用,将省去取地址的步骤,被调用的函数使用&接收即可。适用于任何要修改变量的场景。
指针变量的传递
场景:子函数内修改主函数的一级指针变量。
C语言代码:
#include <stdio.h>
void modify_pointer(int **p,int *q){ // 使用**p接收参数&p,实际就是接收到了p的指针的指针,为二级指针
*p=q;
}
int main() {
int *p=NULL;
int i=10;
int *q=&i;
modify_pointer(&p,q); // p是一级指针,&p为二级指针
printf("after modify_pointer *p=%d\n",*p);
return 0;
}
C++代码:
#include <stdio.h>
void modify_pointer(int *&p,int *q){ // 对一级指针取地址,就是二级指针
p=q;
}
int main() {
int *p=NULL;
int i=10;
int *q=&i;
modify_pointer(p,q); // p、q均为一级指针
printf("after modify_pointer *p=%d\n",*p);
return 0;
}
以上两种编码,结果均为:
F:\Computer\Project\practice\8\8.3-class_a_c\cmake-build-debug\8_3_class_a_c.exe
after modify_pointer *p=10
进程已结束,退出代码为 0
分析:
上述代码中,p本身就是一个指针变量,如果再对其取地址,就是取其二级指针。

以上两个例子,注意C语言和C++写法的区别。简单概括为C++如果对参数进行修改,加上&即可。
2. C++的布尔类型
布尔类型在C语言中没有,是C++的,有true和false。
#include <stdio.h>
int main() {
bool a=true;
bool b=false;
printf("a=%d,b=%d\n",a,b);
return 0;
}
F:\Computer\Project\practice\8\8.3-bppl\cmake-build-debug\8_3_bppl.exe
a=1,b=0
进程已结束,退出代码为 0
说明:在c++中,true为1,false为0。
C++引用和布尔类型,在后面的算法中会大量使用。
作者介绍
江
江小南
V1