c和c++的区别
1.1c和cpp的打印方式
c使用#include “stdio.h”
c++使用#include < iostream>(引用到系统级的文件用<>)(其实#include < iostream.h>,系统级的编译器自动优化了.h),自己创建的以#include "abc.h"格式
c打印方式
#include"stdio.h"
//#include<iostream>
#include"stdlib.h"
int main()
{
printf("Hello World\n");//c风格
system("pause");
//用#include"stdio.h"不用#include<iostream>时会报错,加上#include"stdlib.h"就不会了
return 0;
}
cpp打印方式
//#include"stdio.h"
#include<iostream>
//#include"stdlib.h"
using namespace std;
int main()
{
//printf("Hello World\n");//c风格
cout << "Hello World" << endl;
//不用using namespace std;时
std::cout<<"Hello World" << std::endl;
system("pause");
return 0;
}
1.2c和cpp的bool
c没有bool得添加头文件
#include"stdio.h"
#include"stdlib.h"
//#include<iostream>
#include"stdbool.h"
using namespace std;
int main()
{
bool bow = false;
system("pause");
return 0;
}
cpp有bool
#include<iostream>
using namespace std;
int main()
{
bool bow = false;
system("pause");
return 0;
}
1.3c和cpp的形参引用
1.3.1引用的特性
引用必须初始化
可以被多个对象进行引用
唯一性,一旦引用被初始化,它将始终引用同一个对象。
1.3.2引用实例
cpp支持传引用
#include<iostream>
using namespace std;
struct FHello
{
int a;
int b;
long int c;
};
//c++支持 传引用
void test01(FHello &cc)
{
//如果用FHello cc是产生了一个拷贝效率很低
//FHello &cc引用更高效,比指针还高效
cc.a = 0;
}
//指针占4个字节
void test02(FHello* cc)
{
//把指针指向地址的值拷贝到FHello* cc中
cc->a = 0;
}
int main()
{
FHello o;
test01(o);
test02(&o);
system("pause");
return 0;
}
c不支持传引用
1.3.3引用和指针
定义方式:指针通过使用来声明,例如int ptr;,而引用使用&来声明,例如int& ref = variable;。
绑定对象:指针可以在声明后重新赋值,可以指向不同的对象。而引用在声明时必须初始化,并且一旦绑定到了对象,就无法更改其绑定的对象。
空值:指针可以具有空值(nullptr),表示指针不指向任何有效的对象。而引用必须在声明时绑定到一个对象,不存在空引用的概念。
内存操作:指针可以进行指针运算(如指针的加减、解引用等),可以直接操作对象所在的内存地址。而引用不支持指针运算,它只是对象的别名,可以像使用普通变量一样使用。
作为函数参数:指针可以作为函数参数,通过传递地址来对函数之外的对象进行修改。而引用作为函数参数,可以通过传递引用来对函数之外的对象进行修改,由于引用的特性,会更直观和安全一些。
1.3.4多级指针
多级指针:是指指针的指针,它可以用来指向其他指针的地址。
int num = 10;
int* ptr1 = # // 指向int类型的指针
int** ptr2 = &ptr1; // 指向int*类型的指针,即指向int类型的指针的指针
cout << *ptr1 << endl; // 输出:10,通过一级指针访问num的值
cout << **ptr2 << endl; // 输出:10,通过二级指针访问num的值
1.4c和cpp的结构体
c的结构体不可以直接放函数
#include"stdio.h"
#include"stdlib.h"
struct test02
{
//void Hello() {};//会报错
int a;
};
int main()
{
system("pause");
return 0;
}
c的结构体放函数的方式,初始化
#include"stdio.h"
#include"stdlib.h"
//#include<iostream>
using namespace std;
void Hello1(int a, int b)
{
}
struct test01
{
void (*Hello2)(int,int);
int a;
int b;
}FTs;
void main()
{
//struct test01 FTs;//上面没声明的话}FTs;就得按此行进行声明
FTs.Hello2 = Hello1;
}
cpp的结构体可以放函数
#include<iostream>
using namespace std;
struct test01
{
void Hello1() {};
void Hello2(int a,int b) {};
};
int main()
{
system("pause");
return 0;
}
1.5c和cpp的继承
c没有继承
cpp有继承
#include<iostream>
using namespace std;
struct test01
{
int c;
int d;
};
struct test02 :public test01
{
void Hello(int a, int b) {};
}FTs;
int main()
{
FTs.c;
system("pause");
return 0;
}
struct的权限默认为public