Why can't I overload ostream's << operator?
-
28-10-2019 - |
문제
EDIT: Passed Expression exp and string expression by const reference
I'm trying to allow a class to be display via cout in the following manner:
#include <iostream>
class Expression {
private:
std::string expression;
public:
Expression(const std::string& expression):
expression(expression) { }
friend std::ostream& operator <<(ostream& os, const Expression& exp) {
return os << exp.expression; }
};
however, on compiling I get the errors:
main.cpp(9) : error C2061: syntax error : identifier 'ostream'
main.cpp(9) : error C2809: 'operator <<' has no formal parameters
this is especially confusing because VC++ is giving me ostream
as an autocompletion suggestion when I enter std::
. What's causing these errors, and how can they be resolved?
해결책
Surely you need std::ostream
in all locations? i.e.:
friend std::ostream& operator <<(std::ostream& os, Expression& exp) ...
^^^
다른 팁
Without a using namespace std;
clause (which has its own set of problems), you need to fully qualify all the iostream
stuff.
You can see this with the following program:
#include <iostream>
class Expression {
private:
std::string expression;
public:
Expression(std::string expression):
expression(expression) { }
// added this bit.
// _/_
// / \
friend std::ostream& operator <<(std::ostream& os, Expression& exp) {
return os << exp.expression; }
};
int main (void) {
Expression e ("Hi, I'm Pax.");
std::cout << e << std::endl;
return 0;
}
which prints out:
Hi, I'm Pax.
as expected.
And, as some comments have pointed out, you should pass the string as const-reference:
#include <iostream>
class Expression {
private:
std::string expression;
public:
Expression(const std::string& expression)
: expression(expression) {
}
friend std::ostream& operator <<(std::ostream& os, const Expression& exp) {
return os << exp.expression;
}
};
int main (void) {
Expression e ("Hi, I'm Pax.");
std::cout << e << std::endl;
return 0;
}
제휴하지 않습니다 StackOverflow