Skip to main content
gamedev.net
🔒 Locked

C++ user-defined stream operators for streamable objects

Started by all_names_taken 2 replies 550+ views
Original Post
all_names_taken
all_names_taken
I'm tryin to define an own ">>" operator for an own class i C++. The idea is that I want to be able to write stuff like this:

	OwnClass foobar;
	int blah;
	char something_else;
	fstream file;
	file.open("test.txt");
	if(file.is_open()) {
		file>>blah;
		file>>foobar;
		file>>something_else;
	}


Here's the file test2.h in which I've declared the own object:

#include <fstream>
#include <iostream>
using namespace std;

class OwnClass {
public:
	OwnClass();
	~OwnClass();
	friend istream& operator>> (istream& f, OwnClass& c);
	
private:
	int hello;
	char hello2;
	float hello3;
};

istream& operator>> (istream& f, OwnClass& c);



And finally here's the part of test2.cpp file in which I've defined all the stuff:

istream& operator>> (istream& f, OwnClass& c) {
	f>>c.hello;
	f>>c.hello2;
	f>>c.hello3;
	return f;
}



Now when I try to compile this I get two errors: - a complaint that the operator can't access private members of OwnClass. Why? Shouldn't the friend declaration allow that? - a complaint that the ">>" operator in the main() function (in a file called Test.cpp which includes Test2.h) is ambigious. The code in main is the following:

int main() {
	OwnClass foobar;
	fstream file;
	file.open("test.txt");
	if(file.is_open()) {
		file>>foobar;
	}
}



Preferably I'd like the stream to handle binary files rather than text files. [Edited by - all_names_taken on June 1, 2006 5:41:46 AM]
Enigma
Enigma
What compiler are you using? Your code compiles fine under all three of my compilers.

Please note that putting a using declaration in a header file is evil since every source file that includes that header, whether directly or indirectly, is now implicitly using that symbol or namespace now too, whether it wanted to or not.

Σnigma
Toni Petrina
Toni Petrina
Try
class OwnClass {  //...  friend istream& operator>>(istream &is, OwnClass &ref)  {    //..  }};
So... Muira Yoshimoto sliced off his head, walked 8 miles, and defeated a Mongolian horde... by beating them with his head?

Documentation? "We are writing games, we don't have to document anything".
all_names_taken
all_names_taken
Thank you, the second method with friend defined inside the class worked

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.