【发布时间】: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& operator<<(ostream& sout, const IntList& list)? -
请edit 在您的问题中包含显示此错误的minimal reproducible example。问题可能存在于您的问题中没有的某些代码细节中。
-
@Santeau 我无法复制。:)
-
从您显示的代码中不清楚 operator
-
我希望
operator<<只是说{ list.print(sout); return sout; }。 (并且print和getCapacity被声明为const,并且成员变量是私有的。)