问题描述
我的程序:
class test
{
int k;
public:
void changeval(int i){k=i;}
};
int main()
{
test obj;
int i;
cin>>i;
obj.changeval(i);
return 0;
}
有什么方法可以让我直接将用户的输入作为参数传递给函数changeval(int),甚至不需要初始化i的值??
Is there any way, by which i can directly pass input from the user as an argument to the function changeval(int), without even initializing value to i??
我的意思是,我不想声明一个变量只是为了将值传递给一个函数.有什么办法可以避免吗?如果是,我也可以将它用于构造函数吗?谢谢.
I mean, i don't want to declare a variable just to pass value to a function. Is there any way i can avoid it? If yes, can I use it for constructors also? Thanks.
推荐答案
不.现在,您可以将其放入一个函数中:
Nope. Now, you could put this into a function:
int readInt(std::istream& stream)
{
int i;
stream >> i; // Cross your fingers this doesn't fail
return i;
}
// Then in your code:
obj.changeval(readInt(std::cin));
当然,这仍然会创建一个 int
(它只是将它移动到 readInt
函数).
But of course, this still creates an int
(it just moves it to the readInt
function).
实际上,您必须为int
创建一些对象/内存空间,以便您可以读取它并传递它.可以更改您执行此操作的位置.但简单地回答你的问题:不.
In reality, you have to create some object/memory space for the int
to live in, so you can read it and pass it. Where you do this can be changed. But to simply answer your question: no.
这篇关于使用 cin 将输入作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!