简体   繁体   English

C ++中的函数和变量声明

[英]Functions and variable declaration in C++

In the following code, why must int nInteger be declared inside int readNumber() 's body, but int nAnswer must be declared inside the () portion of void writeAnswer() ? 在下面的代码,为什么一定要int nInteger被内声明int readNumber()的身上,但int nAnswer必须的()部分中声明void writeAnswer() Declaring int nInteger inside the () or declaring int nAnswer inside the function body causes the IDE to complain about too few arguments for said function. 在()内声明int nInteger或在函数体内声明int nAnswer会使IDE抱怨该函数的参数太少。 Why does this happen? 为什么会这样?

I'm using Code::Blocks and the included MinGW on a Windows 7. 我在Windows 7上使用Code :: Blocks和随附的MinGW。

#include <iostream>

int readNumber()
{
    using namespace std;
    cout << "Please enter an integer: ";
    int nInteger;
    cin >> nInteger;
    return nInteger;
}

void writeAnswer(int nAnswer)
{
    using namespace std;
    cout << "The sum is: " << nAnswer << endl;
}

int main()
{

    int x;
    int y;
    x = readNumber();
    y = readNumber();

    writeAnswer(x+y);

    return 0;
}

So basicly the int readNumber() function does not require any argument to be passed. 因此,从根本上说,int readNumber()函数不需要传递任何参数。 You declare a local variable so the function knows where to assign the value you type in. You declare variable int nInteger and then in the very next line you assign a value to it by calling cin >> nInteger . 您声明一个局部变量,以便函数知道在哪里分配您键入的值。声明变量int nInteger ,然后在下一行通过调用cin >> nInteger为其分配一个值。 If there was no variable declared then your program wouldn't know where to store the value that you type in. 如果没有声明任何变量,则您的程序将不知道将键入的值存储在何处。

You can think of it as of a basket for apples. 您可以将其视为苹果的篮子。 You have one basket but no apples in it, then someone gives you 2 apples that you put into the basket. 您只有一个篮子,但没有苹果,然后有人给您2个放入篮子的苹果。 In the end the return statement work like you give the basket to someone else. 最后, return语句的工作就像您将篮子交给其他人一样。

Function void writeAnswer on the other hand requires an argument to be passed. 另一方面,函数void writeAnswer需要传递一个参数。 As you can see there in local variable declared. 如您所见,本地变量已声明。 What it does is to simply display "The sum is: PASSED_ARGUMENT" . 它的作用是仅显示"The sum is: PASSED_ARGUMENT" So basicly if you call your writeAnswer function with number 6 like writeAnswer(6) it will write "The sum is: 6" . 因此,基本上,如果您用数字6调用您的writeAnswer函数writeAnswer(6)例如writeAnswer(6) ,它将写入"The sum is: 6"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM