C++里声明函数原型的作用

#include <iostream>
#include <cmath>
using namespace std;

// 这个声明函数原型的代码必须有, 如果没有的话会报use of undeclared identifier 'simon' 这个异常
void simon(double n);


int main()
{
	simon(3);
	cout << "please input a int num : " << endl;
	double n;
	cin >> n;
	simon(n);
	cout<< "the end" << endl;
    return 0;
}

void simon(double n)
{
	cout<<"simon says n = " << n << endl;
}

如上面所示的代码,  有一个自定义的函数simon, 如果该函数实在main()方法的下方的话,  那么注释下方的哪行代码 void simon(double n); 不写的话就会抛如下的异常:

/tmp/652211883/main.cpp:10:2: error: use of undeclared identifier 'simon'
        simon(3);
        ^
/tmp/652211883/main.cpp:14:2: error: use of undeclared identifier 'simon'
        simon(n);
        ^
2 errors generated.

exit status 1

还有种方法来避免这个问题就是把自定义的方法写到main函数的上方, 如下所示:

#include <iostream>
#include <cmath>
using namespace std;

//void simon(double n);
// 写到main的上方可以避免这个异常
void simon(double n)
{
	cout<<"simon says n = " << n << endl;
}

int main()
{
	simon(3);
	cout << "please input a int num : " << endl;
	double n;
	cin >> n;
	simon(n);
	cout<< "the end" << endl;
   return 0;
}



猜你喜欢

转载自blog.csdn.net/c1392851600/article/details/83870052
今日推荐