接收istream指针的类读取字符时出现绑定错误的技术咨询
cannot bind non-const lvalue reference Error with std::istream::get Let's break down this error and fix it step by step. That error message is telling you: you're trying to pass a temporary char value (an rvalue) to a function that expects a non-const reference to a char (an lvalue). In C++, non-const lvalue references can only bind to modifiable, named variables—literals, temporaries, or const values won't work here.
Looking at your code, the problem centers on this line:
while(is->get(ch)){ // do something }
The std::istream::get(char&) overload needs a modifiable char variable to store the character it reads. Here are the most likely issues and their fixes:
1. You forgot to declare the ch variable in foo
This is the most common culprit. If ch isn't defined inside your foo function, the compiler might misinterpret it (or you simply omitted the declaration entirely). Fix this by adding a local char variable:
void foo(istream *is){ char ch; // Declare a modifiable char variable to hold the input while(is->get(ch)){ // Your logic here—now ch holds each character read from the stream } }
2. ch is a const variable or rvalue
If you defined ch as const char ch; or tried passing a literal like is->get('a'), you'll hit this error because non-const references can't bind to const values or temporaries. Switch to a regular, non-const char variable to resolve this.
3. You're mixing up get overloads
std::istream has two key get methods:
int get(): Reads a character and returns its integer value (orEOFwhen the stream ends)istream& get(char&): Reads a character into the provided variable and returns the stream (for checking state)
If you intended to use the first overload, adjust your code to store the return value in an int (critical to avoid confusing EOF with a valid character):
void foo(istream *is){ int ch; // Use int to capture EOF correctly while((ch = is->get()) != EOF){ char c = static_cast<char>(ch); // Do something with c } }
One quick note: Your stream setup istream is(cin.rdbuf()); is totally fine—it shares cin's buffer, so reading from is will behave the same as reading from cin directly. No issues there.
内容的提问来源于stack exchange,提问作者eatorres

