一个 C++ 程序必须有 main 函数,否则会报错 Undefined symbol: _main。#include <iostream> 是可选的,一个 C++ 程序可以只有 main 函数,但是 std 命名空间(namespace)就不能使用了,它在 iostream 这个头文件里面。
关于头文件,在 C 语言中,头文件会写上扩展名,例如 stdio.h, string.h 等。但是在 C++ 中,头文件的扩展名被省略了。在古老的 C++ 版本中,例如一个 1987 年的 C++ 编译器,里面使用 iostream.h,也就是旧式 C++。来自 C 语言的头文件(转换后的 C)前面会加个 c,例如来自 C 语言的 math.h 在 C++ 中变成了 cmath。C++ 新式风格是没有头文件扩展名了。
C 中头文件扩展名五花八门,有 hxx、hpp,或者 h,最后 ANSI/ISO 委员会觉得太乱套了,最后一致同意不使用任何扩展名。
main 函数
main 函数又叫做主函数。int main(void) {xxx; return 0;} 是 main() 函数,其中 int main(void) 叫做函数头,后面的 {xxx; return 0;} 叫做函数体。
int(数据类型)表示 main 函数的返回类型是整数类型 (integer),return 0; 表示函数的返回值是 0。(void) 表明函数不接受任何参数,括号中写的是函数接受的参数,void 在英文中的解释是'空的'、'空白的'。
#include<iostream>// 函数头intplus(int a, int b, int c); // 此为函数头,也可以简写为 int plus(int, int, int);// 主函数intmain(void){
int result;
int num1 = 2;
int num2 = 3;
int num3 = 6;
result = plus(num1, num2, num3);
std::cout << "Result: " << result << std::endl; // 双引号中间的部分是字符串,可以试试自己修改成别的。return0; // 结束 main() 函数,返回值为 0,但实际上现代 C++ 中可以省略。
} // 函数定义intplus(int a, int b, int c){
return a+b+c;
}
运行结果:
Result:11 Program ended withexit code: 0
如果你在主函数(main 函数)里面加上 using namespace std; 代码会报错,因为 std 名称空间中有同名的、也叫 plus 的内容,这引起了冲突。如果非要使用这个代码,就要把 plus 函数换个别的名字,例如 plus1。
HelloHelloHelloHello Program ended withexit code: 0
你可能会疑惑,上面的代码中为什么多个地方在使用 str 这个名字,这样是否会导致冲突?
其实并不会,C 和 C++ 有'作用域'的概念,作用域就是程序中变量/标识符的有效区域,决定了在哪里可以访问它。下面用几个例子讲解:
局部作用域(函数内):
voidfunc(){
int x = 10; // x 只在 func 内有效// x 可以在这里使用
}
// x 在这里不可访问
块作用域:
{
int y = 20; // y 只在这个{}内有效
}
// y 在这里不可访问if (true) {
int z = 30; // 块作用域
}
如果你把变量/标识符放在任何块和局部作用域外面,那就是全局变量:
#include<iostream>int a = 3; // a 在全局作用域voidvisiablefunc(int b); // 同样,这个函数的位置也在全局作用域,任何地方都可见intmain(void){
int c = 2;
std::cout << a; // a 在任何地方都可见visiablefunc(a);
}
voidvisiablefunc(int b){
std::cout << a; // std::cout << c; // 这会导致报错,因为 c 只在 main 函数里面可见。
}
命名空间作用域:
#include<iostream>namespace myspace {
// 自定义一个命名空间// 函数只在这个命名空间内可见intplus(int a, int b, int c){
return a+b+c;
}
}
intmain(void){
usingnamespace std;
int result;
int num1 = 2;
int num2 = 3;
int num3 = 6;
// plus 函数的返回值被赋值给 result
result = myspace::plus(num1, num2, num3); // 用 myspace::来访问 plus 函数
cout << "Result: " << result << endl;
return0;
}
using namespace std; 引入了命名空间 std,如果直接使用 plus,程序会报错 No viable constructor or deduction guide for deduction of template arguments of 'plus',因为 std 中有叫做 plus 的东西了,准确说这个'东西'是函数对象类,它是这么用的 std::plus<int> add;,虽然不是个函数,却占用了 plus 这个名字。这时候名称空间就发挥了作用,我们自己定义的 plus 是个函数,被我们放在 mysapce 命名空间里面,我们使用的时候用 myspace::plus(xxx) 就能调用 plus 函数,而且不引起冲突,因为 myspace 里面只有一个叫做 plus 的东西。
整数类型有 short, int, long, long long 四种,int 适合多数情况的数字存储。C++ 确保这些类型的最小长度,short 至少 16 位,int 至少和 short 一样长,long 至少 32 位,至少与 int 一样长,long long 至少 64 位,至少与 long 一样长。