C++ 如何实现:myInstance << "abc"<< someInt << std::endl

标签 c++ operator-overloading ostream

我在 C++ 中有我的自定义类:

Class MyClass
{
  private std::ofstream logfile("D:\my.txt",std::ios_base::app);
}

我希望能够编写以下内容:

MyClass *my = new MyClass();
int a = 3;
my <<  "Hello World1" << a << std::endl;
my << L"Hello World2" << a << std::endl;

结果应该是所有内容都将保存(重定向)到名为“logfile”的私有(private)流(文件)中。

这可能吗? 我试图使用 cca 这个,但没有成功: https://www.tutorialspoint.com/cplusplus/input_output_operators_overloading.htm

最佳答案

你可以这样使用:

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";
}

模板化运算符 << 接受编译的所有内容并将其重定向到 MyClass 对象内的 ofstream。 << 运算符必须声明为 MyClass 的友元,因为它是在其外部定义的,并且必须能够访问私有(private)日志文件对象。

如评论中所述,如果您通过指针访问 MyClass 对象,则需要在使用 << 运算符之前取消引用它:

MyClass *obj = new MyClass;

*obj << "Hello\n"; 
*obj << 123 << " World\n";

无论如何,您的类定义中存在一些语法错误(也许这只是为了示例目的?)。

关于C++ 如何实现:myInstance << "abc"<< someInt << std::endl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46462838/

相关文章:

c++ - 如何通过重载运算符 << 来访问 protected 函数? C++

c++ - 使用 C++ 替换 snprintf 和 printf

c++ - GCC:在 OS X 10.11.5 上获取 ld: symbol(s) not found for architecture x86_64 错误

c++ - 对 ofstream::open 的非阻塞调用?

Ruby:重载对实例属性的索引赋值

c++ - 错误 2 错误 C2679 : binary '/' : no operator found which takes a right-hand operand of type (or there is no acceptable conversion)

C++ - ostream、 friend 和命名空间

c++ - 我如何从 wostream 转换为 ostream

c++ - 使用已删除函数 - std::atomic

c++ - 使用内存映射文件是否可能/值得写入/读取 Protocol Buffer ?