目录
一、C与C++的关系
- C++继承了所有的C特性
- C++在C的基础上提供了更多的语法和特性
- C++的设计目标是运行效率与开发效率的统一
二、C到C++的升级
- C++更强调语言的实用性
- 所有的变量都可以在需要使用时再定义(对比:C语言中的变量都必须在作用域开始的位置定义)
- register 关键字请求编译器将局部变量存储于寄存器中
- 在C++中依然支持register 关键字
- C++编译器有自己的优化方式
- C语言中无法获取register变量的地址
- C++中可以取得register 变量的地址
- C++编译器发现程序中需要取register 变量的地址时,register 对变量的声明变得无效
- 在C语言中,重复定义多个同名的全局变量是合法的(C语言中多个同名的全局变量最终会被链接到全局数据区的同—个地址空间上)
- 在C++中,不允许定义多个同名的全局变量
- struct关键字的加强
- C语言中的struct定义了一组变量的集合
- C语言中struct定义的标识符并不是—种新的类型
- C++中的struct用于定义一个全新的类型
C语言中:
typedef struct _tag_student Student; struct _tag_student { const char* name; int age; };
等价于==》
C++中:
struct Student { const char* name; int age; };
三、int f()与int f(void)的区别
3.1、在C语言中
- int f()表示返回值为int,接受任意参数的函数
- int f(void)表示返回值为int的无参函数
3.2、在C++中
- int f()和int f(void)具有相同的意义
- 表示返回值为int的无参函数
3.3、实例说明
#include <stdio.h>
struct Student
{
const char* name;
int age;
};
f(i)
{
printf("i = %d\n", i);
}
g()
{
return 5;
}
int main(int argc, char *argv[])
{
Student s1 = {"Delphi", 30};
Student s2 = {"Tang", 30};
f(10);
printf("g() = %d\n", g(1,2,3,4,5));
return 0;
}
在C++中编译的结果:
这是因为C++中不允许默认类型 ,所以下面程序的写法在C++中是错误的。
f(i)
{
printf("i = %d\n", i);
}
g()
{
return 5;
}
#include <stdio.h>
typedef struct _tag_student Student;
struct _tag_student
{
const char* name;
int age;
};
f(i)
{
printf("i = %d\n", i);
}
g()
{
return 5;
}
int main(int argc, char *argv[])
{
Student s1 = {"Delphi", 30};
Student s2 = {"Tang", 30};
f(10);
printf("g() = %d\n", g(1,2,3,4,5));
return 0;
}
在C语言中编译的结果:
编译通过,且有输出,说明C语言可以默认类型。
四、总结
- C++更强调实用性,可以在任意的地方声明变量
- C++中的register只是一个兼容的作用
- C++编译器能够更好的进行优化
- C++中的任意标识符都必须显示的指明类型