C++ 在另一个函数中调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20925990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:24:22  来源:igfitidea点击:

Calling functions within another function

c++

提问by TThom246

I am writing a program. And in the main function "int main()" i call to a function called, lets say, "int X()". Inside "int X()" I would like to call to another function "void Y()". Any ideas how to do this? I tried, inside the X() function, doing "Y();" and "void Y();" but to no prevail. Any tips on getting this to work? if at all possible?

我正在写一个程序。在主函数“int main()”中,我调用了一个名为“int X()”的函数。在“int X()”中,我想调用另一个函数“void Y()”。任何想法如何做到这一点?我试过,在 X() 函数中,做 "Y();" 和“无效 Y();” 但以不占上风。有什么让这个工作的提示吗?如果可能?

ex.

前任。

#include<iostream>

int X()
{
   Y();
}

void Y()
{
   std::cout << "Hello";
}

int main()
{
   X();
   system("pause");
   return 0;
}

回答by marcinj

You must declare Y() before using it:

你必须在使用它之前声明 Y() :

void Y();

int X()
{Y();}

回答by Shoe

When the compiler reaches:

当编译器达到:

int X()
{
   Y();
}

it doesn't know what Yis. You need to declare Ybefore Xby inverting their declarations:

它不知道是什么Y。需要声明Y之前X通过颠倒它们的声明:

void Y()
{
   std::cout << "Hello";
}

int X()
{
   Y();
}

int main()
{
   X();
   system("pause");
   return 0;
}

You should also provide a return?value for X, otherwise a warning will pop up.

您还应该为 提供return? 值X,否则会弹出警告。

And please, don't follow the suggestion of using using namespace std;. The way you writing std::cout?is just fine.

并且请不要遵循使用using namespace std;. 你写的方式std::cout?很好。

And hereis the working example.

这里是工作的例子。

回答by 3yakuya

You must define or declare your functions before you use them. For example:

在使用它们之前,您必须定义或声明您的函数。例如:

void Y();         //this is just a declaration, you need to implement this later in the code.
int X(){
    //...
    Y();
    //...
    return someIntValue;   //you will get warned if function supposed to return something does not do it.
}

OR

或者

void Y(){
    //code that Y is supposed to do...
}

int X(){
    //...
    Y();
    //...
}

When you call the function you do not write its type anymore (to call functon Y you write: Y(arguments);and not void Y(arguments);). You write the type only when declaring or defining the function.

当你调用函数时,你不再写它的类型(调用函数 Y 你写:Y(arguments);而不是void Y(arguments);)。只有在声明或定义函数时才编写类型。

回答by user2345215

You need to declare the Yfunction before the Xfunction uses it.

您需要YX函数使用它之前声明该函数。

Write this line before the definition of X:

在定义之前写下这一行X

void Y();