Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'ostream')

Tags:

c++

I'm trying to do

cout << Print(cout); However, there is an "invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'ostream')" error when compiling.

#include <iostream>

using namespace std;

ostream& Print(ostream& out) {
  out << "Hello World!";
  return out;
}

int main() {
  cout << Print(cout);
  return 0;
}

Why this doesn't work? How can I fix this? Thanks!!

like image 711
JASON Avatar asked Nov 17 '13 09:11

JASON


1 Answers

The syntax you might be looking for is std::cout << Print << " and hello again!\n";. The function pointer is treated as a manipulator. A built-in operator << takes the pointer to Print and calls it with cout.

#include <iostream>

using namespace std;

ostream& Print(ostream& out) {
  out << "Hello World!";
  return out;
}

int main() {
  cout << Print << " and hello again!\n";
  return 0;
}
like image 108
Potatoswatter Avatar answered Oct 03 '22 08:10

Potatoswatter