C语言面向过程:算法+数据结构 = 程序
C++ 面向对象:算法+数据结构 = 对象 对象+通讯机制=程序
const{
c:const修饰的变量,在c语言里是可以被指针间接修改的
c++:const修饰的变量,不能被修改 }
int main () { const int a = 9; int *p = &a; *p = 7; printf("%d\n",a); } 在c语言中可以通过地址来改变const修饰的变量值,但是在c++不可以
作为C++编译会出现此种错误。
define
c:使用define定义常量
c++:一般不会使用define定义常量,而是用const
引用
int a = 5;
int &b = a;
引用就是取别名,通过形参改变实参
引用的作用
1.作为参数,新参改变就是实参改变
2.作为返回值,返回的是变量本身而不是变量的值(在初学阶段返回的变量本身和变量的值基本没有区别,但是在后面可能会使用结构体作为变量,此时使用引用的方法可以返回整个结构的所有值)
void swep1 (int &a,int &b) //可以通过引用来直接进行变量数值的交换
{
int tmp;
tmp = a;
a= b;
b = tmp;
}
int & setval(int &a) //引用返回变量本身
{
a = 22;
return a;
}
int main(int argc, char *argv[])
{
int a = 7;
int b = 3;
swep1(a,b);
printf("a = %d\n,b = %d\n",a,b);
setval(a);
printf("a = %s\n",a);
int& c = a;
printf("&c = %d---- %d\n",c,a);
return 0;
}
函数重载
相同的函数名,不同的参数(类型,数目,) 行为相似,逻辑不同使用重载
行为相同,逻辑相同应该使用模板
多个相同名字的函数调用时编译器会自动根据给定的变量值和类型进行辨别。需要不同函数之间的给定变量不能有歧义,每一种给定变量的方法只能出现一次。
特别注意在设定函数的默认参数时是否会有冲突。
#include<stdio.h>
int add(int a,int b)
{
printf("111\n");
return a+b;
}
int add(int a,int b ,int c)
{
printf("222\n");
return a + b + c;
}
double add (int a,double b)
{
printf("333\n");
return (double)a+b;
}
double add (double a,double b)
{
printf("444111\n");
return a + b;
}
int main()
{
int a =1,b = 2,c = 3;
double d = 1.253;
add(a,b);
add(a,b,c);
add(a,d);
}
默认参数
注意!!! 默认参数只能写在函数声明中
-
传参只能从左往右
-
默认参数一定是从右到左,给定默认参数要连续,不能有跳跃。
#include <stdio.h>
int add(int a = 1,int b =2 ,int c = 6);
int add(int a,int b,int c)
{
return a+b+c;
}
int main()
{
int a = add();
printf("a = %d\n",a);
int b = add(3);
printf("b = %d\n",b);
b = add(3,6);
printf("b = %d\n",b);
}
NULL
c中NULL表示空指针,是0
c++ nullptr代指无效指针
MUTABLE
mutable修饰的变量可以被更改
mutable不能和const和static直接连用
#include <stdio.h>
struct demo{
int a;
mutable int b;
};
int main()
{
const struct demo A = {100,105};
A.b = 80; //A.a 不能进行修改
printf("%d\n",A.b);
}
此处通过 mutable修饰结构体中的“b”,使得在经过const修饰之后还可以进行修改。
内敛函数
直接展开函数体(效率更高),不需要地址跳转
内联函数必须是和函数体申明在一起才有效。
限制:逻辑简单的函数,不能有switch ,for;如果编译器认为函数不够简单会自动改为普通函数。
使用: 在函数定义前面加上 inline
inline int add(int a,int b)
{
return a+b;
}
int main()
{
int ret = add(5,6);
printf("%d\n",ret);
return 0;
}
空间开辟与释放
c:malloc开辟空间,free释放 (函数)
int *p = (int *)malloc(sizeof(int )*n)
free(p);
c++:new开辟(异常处理失败情况),delete释放 (运算符)
int *p=new int[n]
delete []p;
#include <stdio.h>
int main(int argc, char *argv[])
{
int *p = new int[5];
p[0] = 9;
printf("%d \n",p[0]);
delete []p;
return 0;
}
作用域
c:全局,局部
c++:全局,局部,名词空间,类域
名词空间
#include <stdio.h>
namespace my{
int a = 3;
}
int main()
{
int a = 1;
printf("%d\n",my::a);
}
结果输出 3