1、c++语法检查增强
全局变量检测增强
以上c代码c编译器编译可通过,c++编译器无法编译通过
2、c++对结构体的增强
1、c中定义结构体变量需要加上struct关键字,c++不需要
2、c中的结构体只能定义成员变量,不能定义成员函数。c++即可以定义成员变量,也可以定义成员函数
C语言:
struct stu
{
int num;
char name[32];
/* c语言 不允许在结构体中 定义成员函数
void func(void)
{
printf("我是结构体中的func");
}
*/
};
void test01()
{
//C语言必须加struct
struct stu lucy = {100, "lucy"};
}
C++语言
struct stu
{
int num;
char name[32];
//c++语言 允许在结构体中 定义成员函数
void func(void)
{
printf("我是结构体中的func");
}
};
void test01()
{
//C++语言不用加struct
stu lucy = {100, "lucy"};
//调用结构体中的成员方法(成员函数)
lucy.func();
}
3、c++新增bool类型
void test02()
{
bool mybool;
cout<<"sizeof(bool) = "<<sizeof(bool)<<endl;//1字节
mybool = false;
cout<<"false = "<<false<<endl;//0
cout<<"true = "<<true<<endl;//1
}
4、三目运算符功能增强
1、c语言三目运算表达式返回值为数据值,为右值,不能赋值
void test02()
{
int a = 10;
int b = 20;
printf("C语言:%d\n", a>b?a:b);//20
//a>b?a:b整体结果 右值(不能被赋值)
a>b?a:b = 100;//err不能被赋值
}
2、c++语言三目运算表达式返回值为变量本身(引用),为左值,可以赋值
void test02()
{
int a = 10;
int b = 20;
cout<<"c++中:"<<(a>b?a:b)<<endl;
//a>b?a:b整体结果是变量本身(引用) 左值(能被赋值)
a>b?a:b = 100;//b =100
}