【问题标题】:C++ - Invalid operands to binary expression 'basic_ostream<char>'C++ - 二进制表达式'basic_ostream<char>'的无效操作数
【发布时间】:2021-08-20 22:35:32
【问题描述】:

我有一个带有动态整数数组的“IntList”类,但下面的测试代码片段给我带来了麻烦:

main.cpp

#include <iostream>
#include "IntList.hpp"
using std::cout;
using std::endl;

int main(int argc, const char * argv[]) {
    IntList list{};
    cout << "list-1 -> " << list << endl;
    return 0;
}

IntList.hpp:

#ifndef IntList_hpp
#define IntList_hpp

#include <stdio.h>
using std::ostream;
class IntList
{
public:
    int *dynarray;
    int capacity;
    int used;
    IntList();
    void pushBack(int x);
    int getCapacity();
    void print(ostream& sout);
};
#endif

IntList.cpp

#include <iostream>
#include "IntList.hpp"
using std::cout;
using std::endl;
using std::string;
using std::ostream;

IntList::IntList()
{
    int capacity = 1;
    int used = 0;
    int *dynarray = new int[capacity];
}

ostream& operator<<(ostream& sout, const IntList& list)
{
    for (int i = 0; i < list.used; ++i)
        sout << list.dynarray[i] << " ";
    return sout;
}

据我了解,我尝试使用以下命令重载 invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'ostream') 但我不知道我哪里弄错了,因为 XCode 给了我这个错误:

Invalid operands to binary expression ('basic_ostream<char>' and 'IntList')

知道如何解决这个问题吗?

【问题讨论】:

  • 标题中是否声明了ostream&amp; operator&lt;&lt;(ostream&amp; sout, const IntList&amp; list)?
  • 请edit 在您的问题中包含显示此错误的minimal reproducible example。问题可能存在于您的问题中没有的某些代码细节中。
  • @Santeau 我无法复制。:)
  • 从您显示的代码中不清楚 operator
  • 我希望operator&lt;&lt; 只是说{ list.print(sout); return sout; }。 (并且print 和getCapacity 被声明为const,并且成员变量是私有的。)

标签: c++ iostream ostream


【解决方案1】:

似乎(从您显示的片段中)在头文件 (IntList.hpp) 中没有声明您的 &lt;&lt; 覆盖。因此,main 函数中的代码不(也不能)知道该覆盖,该覆盖在单独的源文件中提供。

您需要在标题中添加该覆盖函数的声明(通常,就在类定义之后),如下所示:

// Declaration (prototype) of the function for which the DEFINITION is provided elsewhere
extern ostream& operator<<(ostream& sout, const IntList& list);

此外,您的IntList 构造函数存在一些严重错误。在其中,您将值分配给三个 local 变量(当构造函数完成时,这些变量的数据将完全丢失)。这些变量隐藏了同名的成员变量。改用这个(即删除int 声明说明符):

IntList::IntList()
{
//  int capacity = 1; // This declares a local variable that hides the member!
    capacity = 1;
    used = 0;
    dynarray = new int[capacity];
}

【讨论】:

  • "此外,您的 IntList 构造函数有一些严重的错误" - 整个类都有缺陷,因为它违反了 Rule of 3。它缺少释放数组的析构函数,以及复制数组的复制构造函数和复制赋值运算符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 2021-09-09
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 2019-07-10
  • 2016-02-11
相关资源
最近更新 更多