C++对C语言增强以及扩展

  • 全局变量检测增强
  • int a ;
  • int a = 10; C下可以,C++重定义
  • 函数检测增强
  • 函数的返回值
  • 形参类型
  • 函数调用参数个数
  • 类型转换检测增强
  • char * p = (char *)malloc(64) C++下必须等号左右一致类型
  • struct 增强
  • C++可以在结构体中放函数
  • 创建结构体变量 可以简化关键字struct
  • bool数据类型扩展
  • C++才有bool类型
  • 代表真 — 1 true 假 ---- 0 false
  • sizeof = 1
  • 三目运算符增强
  • C语言下返回的是值
  • C++语言下返回的是变量
  • const增强
  • C语言下
  • 全局const 直接修改 失败 间接修改 语法通过,运行失败
  • 局部 const 直接修改 失败 间接修改 成功
  • C++语言下
  • 全局 const 和C结论一样
  • 局部 const 直接修改失败 间接修改 失败
  • C++const可以称为常量

.c文件(c文件)

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//1、全局变量检测增强
int a;
int a = 10;

//2、函数检测增强  返回值没有检测  形参类型没有检测   函数调用参数个数没有检测
getRectS( w  , h)
{

	return w *h;
}
void test01()
{
	printf("%d\n", getRectS(10, 10, 10));
}


//3、类型转换检测增强
void test02()
{
	char * p = malloc(64); 
}


//4、struct增强
struct Person
{
	int age;
	//void func(); C语言下 结构体不可以有函数
};

void test03()
{
	struct Person p; //创建结构体变量时候,必须加关键字struct
	p.age = 100;
}


//5、bool类型扩展  C语言下 没有这个类型
//bool a;


//6、三目运算符增强
void test04()
{
	//?:
	int a = 10;
	int b = 20;

	printf("ret = %d\n", a > b ? a : b);

	*(a > b ? &a : &b) = 100;  //C语言下 返回的是值  20 = 100

	printf("a = %d\n", a);
	printf("b = %d\n", b);

}


//7、const增强
//全局const
const int m_A = 100; // 受到常量区保护,运行修改失败

void test05()
{
	//m_A = 200;
	//int * p = &m_A;
	//*p = 200;

	//局部const
	const int m_B = 100; //分配到栈上
	//m_B = 200;
	int * p = &m_B;
	*p = 200;

	printf("%d\n", m_B);

	//int arr[m_B]; 在C语言下 const是伪常量,不可以初始化数组

}


int main(){
	
	//test01();
	//test04();
	test05();


	system("pause");
	return EXIT_SUCCESS;
}

.cpp 文件(c++文件)

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

//1、全局变量检测增强  C++检测出重定义
int a;
//int a = 10;

//2、函数检测增强 返回值检测、形参类型检测、函数调用参数个数
int getRectS(int w,int h)
{

	return w *h;
}
void test01()
{
	printf("%d\n", getRectS(10, 10));
}


//3、类型转换检测增强
void test02()
{
	char * p = (char *)malloc(64);
}

//4、struct增强  C++可以放函数,创建结构体变量,可以简化关键字 struct
struct Person
{
	int age;
	void func()
	{
		age++;
	}
};

void test03()
{
	Person p;
	p.age = 17;
	p.func();
	cout << "p的age = " << p.age << endl;
}

//5、bool类型扩展  C语言下 没有这个类型  C++有bool类型
bool flag = true; // bool类型 代表  真和假   true  ---- 真(1)    false  ---- 假(0)

void test04()
{
	cout << sizeof(bool) << endl; //结果是1个字节
	//flag = false;
	//flag = 100; //将非0的数都转为1
	cout << flag << endl;
}

//6、三目运算符增强
void test05()
{
	//?:
	int a = 10;
	int b = 20;

	printf("ret = %d\n", a > b ? a : b);

	(a < b ? a : b )= 100; // C++下返回的是变量  b = 100

	printf("a = %d\n", a);
	printf("b = %d\n", b);
}


//7、const增强
//全局const   和C语言结论一致
const int m_A = 100;
void test06()
{
	//m_A = 200;
	//int * p = (int *)&m_A;

	//*p = 200;


	//局部const
	const int m_B = 100;
	//m_B = 200;
	int * p = (int *)&m_B;
	*p = 200;
	cout << "m_B = " << m_B << endl;

	int arr[m_B]; //C++下const修饰的变量 称为常量 ,可以初始化数组

}


int main(){
	//test01();
	//test03();
	//test04();
	//test05();
	test06();


	system("pause");
	return EXIT_SUCCESS;
}