关于函数的返回类型
about return type from a function
在这里,我写了一些代码,从一个函数中获得一个数字的平方,但返回语句不像我想要的那样工作,它给了我相同的数字,我已经进入,我想知道背后的原因,请如果有人可以解释这个给我…
#include<iostream>
#include<conio.h>
using namespace std;
int square(int &i);
int main()
{
cout<<"enter the number whose square you want to find";
int a;
cin>>a;
square(a);
cout<<"the square of the number is"<<a;
_getch();
return 0;
}
int square(int &i)
{
return i*i;
}
您忽略了返回值。您应该将其存储为:
int value = square(a);
cout<<"the square of the number is "<< value;
同样,由于类型只是整型,通过引用传递不会给您带来太多好处。出于可读性考虑,我建议使用按值传递:
int square(int i)
{
return i*i;
}
,
或者如果你正在尝试引用,并试图学习它,那么在这种情况下,我会说你必须将product的结果存储在参数本身中,如:
int square(int &i)
{
i = i * i; //this updates i here, and at the call site as well
return i;
}
或者简单地这样做:
int square(int &i)
{
return i = i*i; //multiply, update, and return - all in one statement!
}
未获取结果。你的台词应该是:a = square(a);
从函数中获取结果。另一种可能是写入函数
int square(int &i)
{
i = i * i;
return i;
}
后者将改变传递给函数的变量,从而证明传递引用是合理的。
要想清楚地表明你想改变变量,可以这样做:
void square(int &i)
{
i = i * i;
}
你看这里没有返回,但是它会改变变量的值
你有一个选择:
- 修改传入的参数,或者
- 返回一个值并将其赋值给调用范围内的某个对象。
你在square
中所做的是第二个选择。你似乎想要前者。
如果你真正想要的是修改传入的值,那么你需要这样做:
void square(int &i)
{
i = i*i;
}
或这样做:
a = Square (a) ; // in main()
...
int Square (int i) // Pass by value -- doesn't change a in main
{
return i * i ;
}
或这样做:
Square (a) ; // in main()
...
void Square (int& i) // Pass by reference -- changes a in main
{
i = i * i ; // No need for a return value
}
在编写其他程序之前,请确保理解它们的区别!
从你对答案的评论来看,你误解了引用传递的作用,或者你误解了返回。
我假设你认为变量I将在你的程序中被更新。然而,事实并非如此。如果你做了像…
i = i*i;
那么是的,你是正确的。但是,您没有给i赋任何值,您只是将其自身乘以并返回结果。此外,如果您确实希望基于引用使此工作,则不需要返回任何内容,因为变量将通过引用更新。
相关文章:
- 如何获取std::result_of函数的返回类型
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 在 c++ 中将函数返回类型指定为模板参数
- 使用 SWIG 更改生成的 CS 函数中的返回类型
- C++ 这里有一个返回 (24) 的布尔返回类型函数
- 使用SFINAE来检测void返回类型函数的存在
- 模板返回类型函数如何在C++中工作
- 如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )
- Bon appetit :从 int 返回类型函数在 main() 中打印字符串
- 在引用或指针返回类型函数上输入
- 在后面的返回类型函数语法中,auto关键字背后是否有意图
- 我可以在c++中重写字符串返回类型函数吗?