C++退货声明不起作用
C++ Return Statement Not Working
我刚刚开始学习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;
}
相关文章:
- 在函数中声明的 ifStream 对象在发布模式下不起作用
- 转发声明在命名空间中不起作用的替代方法
- 当我尝试在函数内声明一个函数时,它不起作用?有什么建议吗?*源代码如下*
- 为什么在这种情况下,前向声明不起作用?
- 为什么重载运算符>在参数声明 const 时不起作用?
- 线程函数参数的前向声明不起作用
- 模板函数声明为 void - 代码不起作用?
- 模板化友元声明在 G++ 5.4.0 下不起作用 - 编译器错误或错误代码
- 在声明节点创建链接列表时,为什么静态内存分配不起作用
- 我无法正确获取这些变量声明...为什么这些参数不起作用?我只是将 n 值设置为数组长度
- C++中的友元成员函数 - 转发声明不起作用
- 代码块 HelloWorld C 示例不起作用:未声明错误"ptrdiff_t"
- 如果我将类声明为常量,程序不起作用...而不是康特斯普?
- 基本前向声明不起作用
- 前向声明枚举类不起作用
- C++退货声明不起作用
- 需要帮助无法弄清楚为什么我的头文件函数声明不起作用
- Fedora 18上的Eclipse 4.2.2打开声明不起作用
- 在模板类中声明模板成员变量在 Xcode 中不起作用
- 模板'using'声明不起作用