C++ 学习笔记 1 - 与 Java 的不同
我们看一段代码先
#include <iostream> //包含c++的标准输入输出头文件iostream。 iostream 文件的位置:C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include using namespace std; //这个相当于 java 中的 import java.lang. 但是它用 namespace int show(int x ,int y) //先创建一个 show() 方法 { cout<<"Going to print: " << x+y << endl; return x+y; } int main() { show(5,6); //调用 show() 方法 }
注意,上面代码是先定义了一个 show(), 然后再 main() 中调用 show()
但是,如果把 main() 函数放在最上面,show()移到他的下面,如下,会怎样呢?
#include <iostream> //包含c++的标准输入输出头文件iostream using namespace std; //这个相当于 java 中的 import java.lang. 但是它用 namespace int main() { show(5,6); //调用 show() 方法 } int show(int x ,int y) //先创建一个 show() 方法 { cout<<"Going to print: " << x+y << endl; return x+y; }
结果是不行的!!!!因为 main() 找不到 show()。 然而, 这在 JAVA 中是没有问题的。
报的错误如下:1>d:\cplusplusspace\testconsole\testconsole\test.cpp(6): error C3861: 'show': identifier not found
所以,如果想把main()放在最前面,必须先声明 show().改成:
#include <iostream> using namespace std; int show(int, int); //先声明 show(),然后 main()才能在后面去找他。 int main() { show(5,6); //调用 show() 方法 } int show(int x ,int y) { cout<<"Going to print: " << x+y << endl; return x+y; }
浙公网安备 33010602011771号