Reputation: 1183
I have my custom class in C++:
Class MyClass
{
private std::ofstream logfile("D:\my.txt",std::ios_base::app);
}
I want to be able to write following:
MyClass *my = new MyClass();
int a = 3;
my << "Hello World1" << a << std::endl;
my << L"Hello World2" << a << std::endl;
Result should be that everything will be saved (redirected) into the private stream (file) named "logfile".
Is it possible? I was trying to use cca this, but without success: https://www.tutorialspoint.com/cplusplus/input_output_operators_overloading.htm
Upvotes: 1
Views: 92
Reputation: 329
You can use something like this:
class MyClass
{
public:
MyClass() : logfile("logfile.log", std::ios::app) {}
template<typename T>
friend MyClass& operator<<(MyClass& obj, const T& data);
private:
std::ofstream logfile;
};
template<typename T>
MyClass& operator<<(MyClass& obj, const T& data) {
obj.logfile << data;
return obj;
}
int main() {
MyClass obj;
obj << "Hello\n";
obj << 123 << " World\n";
}
The templated operator << accepts everything that compiles and redirects it to the ofstream inside the MyClass object. The << operator has to be declared as friend of MyClass since it is defined outside it and it has to be able to access the private logfile object.
And as mentioned in the comments, if you access your MyClass object through a pointer you need to dereference it before using the << operator:
MyClass *obj = new MyClass;
*obj << "Hello\n";
*obj << 123 << " World\n";
Anyway you have some syntax errors in your class definition (maybe it was just for example purposes?).
Upvotes: 1