Can a variable be initialized with an istream on the same line it is declared? [duplicate]

﹥>﹥吖頭↗ 提交于 2020-02-01 00:43:07

问题


Can the following two lines be condensed into one?

int foo;
std::cin >> foo;

回答1:


The smart-ass answer:

int old; std::cin >> old;

The horrible answer:

int old, dummy = (std::cin >> old, 0);

The proper answer: old has to be defined with a declaration before it can be passed to operator>> as an argument. The only way to get a function call within the declaration of a variable is to place it in the initialization expression as above. The accepted way to declare a variable and read input into it is as you have written:

int old;
std::cin >> old;



回答2:


You can... with

int old = (std::cin >> old, old);

but you really should not do this




回答3:


Using a function:

int inputdata()
{
    int data;
    std::cin >> data;
    return data;
}

Then:

int a=inputdata();

For data itself:

int inputdata()
{
    static bool isDataDeclared=false;
    if (isDataDeclared==true)
    {
    goto read_data;
    }
    else
    {
        isDataDeclared=true;
    }
    static int data=inputdata();
    return data;
    read_data:
    std::cin >> data;
    return data;
}



回答4:


Maybe not for int, but for your own types:

class MyType {
    int value;
public:
    MyType(istream& is) {
        is >> *this;
    }

    friend istream& operator>>(istream& is, MyType& object);
};  

istream& operator>>(istream& is, MyType& object) {
    return is >> object.value;
}

Then you can create the type with the istream passed to the constructor:

int main() {
    istringstream iss("42");
    MyType object(iss);
}


来源:https://stackoverflow.com/questions/14914688/can-a-variable-be-initialized-with-an-istream-on-the-same-line-it-is-declared

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!