C++退货声明不起作用

C++ Return Statement Not Working

本文关键字:不起作用 声明 C++      更新时间:2023-10-16

我刚刚开始学习C++,在实现返回语句时遇到了问题。我已经能够轻松地将数据传递给新功能,但我对让它返回并不高兴。

我已经编写了我能想到的最简单的代码来尝试调试出了什么问题,但我仍然无法解决。我没有尝试传递太多返回值,而且我也有一个正确的函数类型要传递。它似乎不起作用?

我在Macbook Pro上使用Xcode 4:

#include <iostream>
using namespace std;
int agenext (int age);
int main ()
{   int age;
    cout << "What's Your Age? n";
    cin >> age;
    cout << "Your Current Age: " << age;
    agenext(age);
    cout << endl << "A year has passed your new age is: ";
    cout << age;
}
int agenext (int x)
{
    x++;
    cout << endl << "Your Next Birthday is " << x;
    return x;
}

它返回完美查找。您只是没有设置它返回的任何值。

age = agenext(age)

是您要查找的内容,或者您可以传递指向age变量的指针或引用。

return ing只是成功的一半,另一半是将该值分配给某些东西。 考虑更改:

agenext(age);

age = agenext(age);

现有的两个答案都是正确的;如果你想return一个值,就需要在某个地方分配它。

为了将来参考,您还可以通过跳过return并通过引用而不是值传递age来执行所需的操作。

void agenext (int &x)
{
    x++;
    cout << endl << "Your Next Birthday is " << x;
    /* the value change WILL show up in the calling function */
}

在你的主函数中,你需要另一个变量来保存从 age 函数返回的新年龄。

int main ()
{   int age, newAge;
    cout << "What's Your Age? n";
    cin >> age;
    cout << "Your Current Age: " << age;
    newAge = agenext(age);
    cout << endl << "A year has passed your new age is: ";
    cout << newAge;
    return 0;
}