如何解决在对策函数中调用另一个函数会导致错误为什么?
我有两个函数fun()和fun2();
fun()会在递增全局变量a = 0时调用自身,如果a == 5则终止。但是,如果我调用另一个称为fun2()的函数,该函数基本上返回并且什么也不做,则发生构建错误。为什么? 我只是在尝试递归,却遇到了这个错误。
#include<iostream>
using namespace std;
int a = 0;
void fun() {
if (a == 5)
return;
a++;
fun();
fun2(); //This is where the trouble happens
}
void fun2() {
return;
}
int main() {
fun();
return 0;
}
解决方法
使用它们之前,必须先声明或定义函数。
#include<iostream>
using namespace std;
int a = 0;
void fun2(); // add this (declaration of function fun2)
void fun() {
if (a == 5)
return;
a++;
fun();
fun2(); //This is where the trouble happens
}
void fun2() {
return;
}
int main() {
fun();
return 0;
}
,
您将收到类似的错误
void fun() {
fun2();
}
void fun2() {}
int main() {
fun();
}
该错误与递归无关。您需要先删除函数,然后才能调用它:
#include<iostream>
void fun2(); // declaration
void fun() {
// ...
fun2();
}
void fun2() { } // definition
int main() {
fun();
return 0;
}
...或在fun2
之前简单定义fun
。
“为什么?”
嗯,不是因为递归。
在这种情况下,这样做的部分原因是您的代码是c样式的,大多数情况下确实需要声明您的代码调用的用户定义函数。
您使用c ++标记了此帖子,但没有使用一个类。
例如,如果将这些函数封装在一个类中,则c ++编译器将(通常)找到函数,即使没有事先声明也是如此。
示例:
在下面,我将您的代码封装在一个仿函数(简化的c ++类)中
而且,因为您的代码没有输出,所以我在一些位置添加了cout,以直观地演示代码的编译和功能的执行。
#include <iostream>
using std::cout,std::cerr,std::endl,std::hex,std::dec,std::cin;
#include <string>
using std::string,std::to_string;
int a = 0; // still global,though many discourage use
// functor ... a simple class
class F705_t // ctor and dtor are compiler provided defaults
{
public:
// main() enters at this function
int operator()(int argc,char* argv[])
{
return exec(argc,argv); // exec not yet declared!
}
private:
int exec(int,char** ) // line 31
{
cout << "\n F705_t::exec()";
fun(); // using fun() before declared
cout << endl;
return 0;
}
void fun() // line 37
{
cout << "\n F705_t::fun()" << " a: " << a;
if (a == 5)
return;
a++;
fun(); // recursive call
fun2(); // using fun2() before declared
}
void fun2() // line 47
{
cout << "\n F705_t::fun2()" << " a: " << a;;
return;
}
} // class F705_t
// main() is a c-ism,// and is required of the user in most (but not all) c++ environments
int main(int argc,char* argv[]) { return F705_t()(argc,argv); }
// how invoke a functor --------^^^^^^^^^^^^^^^^^^^^
输出:
F705_t::exec()
F705_t::fun() a: 0
F705_t::fun() a: 1
F705_t::fun() a: 2
F705_t::fun() a: 3
F705_t::fun() a: 4
F705_t::fun() a: 5
F705_t::fun2() a: 5
F705_t::fun2() a: 5
F705_t::fun2() a: 5
F705_t::fun2() a: 5
F705_t::fun2() a: 5
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。