[英]std::cin directly to a function
最近,我遇到了以下代码部分。 我不知道这是否有意义,我只是想了解一下:
#include <iostream>
class foo{
private:
int memeber;
public:
int &method(){ return memeber; }
};
int main(){
foo bar;
std::cin >> bar.method();
}
我以前从未见过这样的东西。 我很惊讶它甚至可以编译。 您如何直接将cin定向到函数地址? 有人可以详细说明它的作用以及是否可以用于任何用途吗?
这段代码:
std::cin >> bar.method();
可以更详细地重写:
int &ref = bar.method();
std::cin >> ref;
因此,调用int
method()
结果将传递给std::cin.operator>>()
有人可以详细说明它的作用以及是否可以用于任何用途吗?
bar.method()
返回对foo::memeber
bar.method()
的引用,该引用可用作左值。
您如何直接将cin定向到函数地址?
这不是函数地址 。
int &method(){ return memeber; } // ^
正如@Lightness 提到的那样,这有点令人困惑。 更好(更清晰)的书写风格可能是
int& method(){ return memeber; }
// ^ makes it more clear that it's a int reference and not address of the function
左值可以与其他任何左值(即变量)一起与std::istream& operator>>(std::istream&,T&)
运算符一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.