C过度C++

1、最直观的不同点就是文件后缀不同。C语言使用.c,C++使用.cpp

2、标准输入输出头文件

C引入标准输入输出头文件       #include<stdio.h>

C++引入标准输入输出头文件   #include<iostream>。当然C++也可以#include<stdio.h>,因为C++完全兼容C

3、输出打印语句

C语言使用printf,换行用 \n。而且printf输出时需要使用格式字符来标定输出的数据类型

C++使用cout,换行用 endl。不需要使用格式字符来标定输出的数据类型

int i = 10;
printf("%d", i);
std::cout << i << std::endl;
View Code

4、C要求先定义在使用,不能边定义边使用。定义放在最前面。

如下C代码(test.c)在Linux下编译不过

#include<stdio.h>
void main()
{
    for ( int i = 0; i < 10; i++)
    {
        printf("i=%d\n", i);
    }
    return;
}
View Code

报错

[root@localhost ~]# gcc test.c
test.c: In function ‘main’:
test.c:4:2: error: ‘for’ loop initial declarations are only allowed in C99 mode
  for (int i = 0; i < 10; i++)
View Code

如果改后缀为test.cpp则可以编译通过,C++允许边定义边使用。当然C++对main返回值也比C严格

#include<stdio.h>
int  main()
{
    for (int  i = 0; i < 10; i++)
    {
        printf("i=%d\n", i);
    }
    return 0;
}
View Code

5、C没有命名空间,C++有

6、C不允许重载,C++允许

 

猜你喜欢

转载自www.cnblogs.com/kelamoyujuzhen/p/9419648.html
C++