Original Post
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: Here's the file test2.h in which I've declared the own object: And finally here's the part of test2.cpp file in which I've defined all the stuff: 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: 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]
OwnClass foobar;
int blah;
char something_else;
fstream file;
file.open("test.txt");
if(file.is_open()) {
file>>blah;
file>>foobar;
file>>something_else;
}
#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);
istream& operator>> (istream& f, OwnClass& c) {
f>>c.hello;
f>>c.hello2;
f>>c.hello3;
return f;
}
int main() {
OwnClass foobar;
fstream file;
file.open("test.txt");
if(file.is_open()) {
file>>foobar;
}
}