1

所以我有这条线:

ArrayList<Operation> operations();

现在,这是我的 ArrayList 类和我的 Operation 结构:

typedef struct Operation {
    char key; 
    int value;
} Operation;
template <class DT>
class ArrayList
{
private:
    int _capacity;
    int _size;
    DT* elements;
public:
    ArrayList();
    ~ArrayList();
    void insert (DT&);
    DT& operator[] (int);
};
ArrayList<DT>::ArrayList()
{
    _capacity = 10;
    _size = 0;
    elements = new DT[10];
}

我认为不需要发布其他方法的代码,因为那里没有发生错误。但是,如果您想看到它们,您只需要询问即可。

现在,每次我尝试做类似的事情

operations.insert(x) //assuming x is a struct that exists.

或者

operations[i].key; //assuming i is a declared and initialized index.

它给了我error C2228: left of (fill in the blank) must have class/struct/unionerror C2109: subscript requires array or pointer type

我已经看过一个关于这个问题的先前线程,我认为我的问题是编译器将我提供的第一行代码作为声明,但没有初始化。但是我没有看到解决方案。在我的脑海中,唯一的解决方案是让它成为一个指针并使用= new ...,但在我的脑海里,关键字new是肮脏的同义词,所以我只是想把它变成一个对象。有什么办法可以解决这个问题?或者我错了,这与对象类型是 a 有关,struct因为这是我第一次使用structs。

4

1 回答 1

2

这一行:

ArrayList<Operation> operations();

声明一个返回的函数ArrayList<Operation>

这通常被称为最令人头疼的解析

要声明您的ArrayList<Operation>,请删除括号:

ArrayList<Operation> operations;
于 2012-11-28T22:12:08.453 回答