使用cin将输入作为函数参数传递 [英] Passing input as a function argument using cin

查看:467
本文介绍了使用cin将输入作为函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序:

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将输入作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆