【问题标题】:Helper Operator Issue in C++C++ 中的辅助运算符问题
【发布时间】:2014-04-15 23:23:01
【问题描述】:

尝试在辅助运算符中返回我的操作系统时,我遇到了一个奇怪的错误。这是代码:

std::ostream operator<<(std::ostream& os, const Item& i) {
    i.display(os);
    return os;
}

我正在使用的编译器告诉我它无法访问,但我不知道为什么或如何修复它。有什么想法吗?

【问题讨论】:

    标签: c++ operator-overloading iostream


    【解决方案1】:

    std::ostream 不可复制,应通过引用返回

    std::ostream& operator<<(std::ostream& os, const Item& i)
    //          ^
    

    【讨论】:

    • 更重要的是,您不想返回一个新的 ostream,而是返回传入的那个。
    • 所以我基本上不自己返回os?
    • @user3075178 没错。并且编译器不允许你这样做。
    【解决方案2】:

    您定义了您的 operator

    【讨论】:

    • 谢谢莎拉。我已经尝试过编译器告诉我类型名称不允许的那个坚果
    • 你能把修改后的代码和错误信息粘贴到这里吗?
    • 问题可能出在 Item...display() 需要是 public 和 const: struct Item { void display( std::ostream & ) const {} };
    猜你喜欢
    • 2021-10-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多