创建函数的位置问题
以下是为了达到同一目的而写的两个不同的简单程序,但是第一个可以执行,第二个执行不了(还望各位高手多多指教):
/*创建一个简单的函数并调用 正确版本
#include <iostream>
void show()
{
std::cout<<"hello world"<<std::endl;
}
//注意创建函数的位置
int main()
{
std::cout<<"the start of main"<<std::endl;
show();
std::cout<<"the end"<<std::endl;
}
*/
/*错误版本,两者不同在于show函数创建的顺序
#include <iostream>
int main()
{
std::cout<<"the start of main"<<std::endl;
show();
std::cout<<"the end"<<std::endl;
}
void show()//创建的函数放在了后面
{
std::cout<<"hello world"<<std::endl;
}
*/
[解决办法]
呵呵,这是基本功啊,后定义,先使用的函数,必须在使用前加上函数说明的。这样改一下就行:
#include <iostream>void show();int main(){std::cout<<"the start of main"<<std::endl;show();std::cout<<"the end"<<std::endl;}void show()//创建的函数放在了后面{std::cout<<"hello world"<<std::endl;}
[解决办法]
main函数调用的时候没有找到你的函数,函数都是要先定义或者声明才能使用的。c语言刚讲函数的时候老师就会讲到这个问题,你加一个前置声明就可以。
在main函数前边加
void show();