[英]C++ How to implement: myInstance << "abc" << someInt << std::endl
I have my custom class in C++:我在 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".结果应该是所有内容都将被保存(重定向)到名为“logfile”的私有流(文件)中。
Is it possible?是否可以? I was trying to use cca this, but without success: https://www.tutorialspoint.com/cplusplus/input_output_operators_overloading.htm
我试图使用 cca 这个,但没有成功: https : //www.tutorialspoint.com/cplusplus/input_output_operators_overloading.htm
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.模板化操作符 << 接受编译并将其重定向到 MyClass 对象内的 ofstream 的所有内容。 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.
<< 运算符必须声明为 MyClass 的朋友,因为它是在它之外定义的,并且必须能够访问私有日志文件对象。
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 对象,则需要在使用 << 运算符之前取消引用它:
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?).无论如何,您的类定义中有一些语法错误(也许只是出于示例目的?)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.