函数的顺序不允许我用c ++编写可重用的代码

时间:2015-06-24 08:43:45

标签: c++

我有两个相互依赖的函数,但C ++中函数的顺序限制了我编写可重用代码的能力。例如,我想在函数B中使用functionA,然后

functionB has to be above functionA.

但是如果

functionB正在使用functionA而functionA也正在使用functionB?它会给出错误

这是代码,以及c ++中函数的顺序

void getAnswer(string answer) {

            mainProgram();

}

void mainProgram() {
   getAnswer("awesome");

}

int _tmain(int argc, _TCHAR* argv[])
{   

    mainProgram();


    return 0;
}

正如您所见,mainProgram()使用的是getAnswer()函数,反之亦然。

我可以通过删除getAnswer()函数来解决这个问题,只需将getAnswer()中的每个代码抛出到mainProgram()但问题是,我会写一个重复代码大约5次,它会看起来很乱。

3 个答案:

答案 0 :(得分:5)

您需要转发声明您的功能:

//forward declaration
void mainProgram();

void getAnswer(string answer) {
    //sees the declaration above, doesn't need the definition
    mainProgram();
}

//now we define the function
void mainProgram() {
   getAnswer("awesome");
}

这种事情应该在你的介绍性书中介绍。如果你没有一本好的入门书,get one

另请注意,您需要在某个时刻终止此相互递归。

答案 1 :(得分:3)

您要找的是forward declaration

首先定义函数的名称和参数,然后声明它们的主体。这允许两个函数相互依赖。

void mainProgram(); // this is a declaration of your function.

void getAnswer(string answer) // the body of the function which can call the declared function.
{
    mainProgram();
}

void mainProgram() // the body of the function which was declared earlier.
{
    getAnswer("awesome");
}

答案 2 :(得分:0)

在这种情况下,它是无限的函数调用。但是如果你不确定订单函数调用和它的声明,请在文件的开头使用forward声明。