【发布时间】:2019-05-31 16:54:28
【问题描述】:
错误 C2676 二进制 '[': 'collection::item' 未定义此运算符或转换为预定义运算符可接受的类型
我阅读了一些帖子和 Microsoft VS 网站,但不明白如何解决问题
template<typename T1, typename T2>
class collection {
private:
class item {
public:
T1 item; T2 key;
};
unsigned int top;
item array = new item[top];
public:
collection& operator[](unsigned int i) {
return array[i];
}
collection(int top) {
this->top = top;
}
void coutarr() {
for (int i = 0; array[i] != 0; i++) {
cout << array[i].item << endl;
}
}
void extendarray() {
item x = new item[top*2];
for (int i = 0; i < top; i++) {
x[i] = array[i];
}
delete []array;
swap(array, x);
top = top*2;
}
void addvar(int i, T1 item, T2 key) {
array[i].item = item; array[i].key = key; //Here 2 Errors
}
};
如果有人能解释我该怎么做,我将不胜感激。谢谢。
【问题讨论】:
-
这点信息很难说,但我假设您的
item类不提供operator=的实现(或复制构造函数)。你能展示你的item课程吗? -
@JoelBodenmann item 是一个嵌套类,
class item { public: T1 item; T2 key; }; -
@Keanu 此声明 item array = new item[top];无效。
-
只是猜测:top 没有价值。这使得数组的长度充其量为零(这真的很糟糕),最坏的情况是未定义的行为。
-
我猜
item array = new item[top];应该是一个指针:item *array = new item[top];
标签: c++ visual-studio class compiler-errors declaration