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

本文探讨了C++中函数声明与定义的重要性,特别是在函数调用前未声明时出现的编译错误。通过实例说明了如何正确声明和定义函数以避免此类错误,强调了函数原型声明的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值