重载*运算符时无法转换错误

时间:2017-03-09 18:58:09

标签: c++ operator-overloading

我有像这样的DynamicArrayIterator类

template <class T> class DynamicArrayIterator{
private:
    int currentPosition;
    DynamicArray<T>* array; //pointer to the dynamic array
    int direction; //1 indicates forward, -1 indicates backwards  
public:
    DynamicArrayIterator(DynamicArray<T>* dyn, int pos, int dir){
    array = dyn;
    currentPosition = pos;
    direction = dir;
    }
    T operator *(){
    T t = array[currentPosition];
    return t;
    }
    void operator ++(){
    this->currentPosition += this->direction;
    }

DynamicArray类设置为

template <class T> class DynamicArray{

private:
    T *storage;
    int cur; //next position available
    int max; //capacity
public:
    DynamicArray(); //constructor
    ~DynamicArray(); //destructor
    void add(T item);
    T remove(int i);
    int size();

/*20*/  T& operator [](int i){ //selected if object called on is not const
    return storage[i];
    }
    T operator [](int i)const{ //selected if called by a const object
    return storage[i];
    }
    DynamicArrayIterator<T> begin(){
    return DynamicArrayIterator<T>(this, 0, 1);
    }
    DynamicArrayIterator<T> end(){
    return DynamicArrayIterator<T>(this, this->cur, 1);
    }
    DynamicArrayIterator<T> r_begin(){
    return DynamicArrayIterator<T>(this, 0, -1);
    }
    DynamicArrayIterator<T> r_end(){
    return DynamicArrayIterator<T>(this, this->cur, -1);
    }
};

我在重载*运算符时遇到问题;我希望能够直接获取和设置值;我称之为:

int main(){
    DynamicArray<int> foo;
    foo.add(3);
    foo.add(2);
    cout << foo[1] << endl;
    foo[1] = 10;
    cout << foo[1] << endl;
    DynamicArrayIterator<int> a = foo.begin();
    ++a;
    cout << *a << endl;
}

并收到错误

DynamicArray.cpp:98:29: error: cannot convert ‘DynamicArray<int>’ to ‘int’ in initialization
  T t = array[currentPosition];

我哪里错了?

3 个答案:

答案 0 :(得分:2)

应该是

public DOMElement DOMDocument::getElementById ( string $elementId )

答案 1 :(得分:1)

在你的迭代器中,你有DynamicArray<T>* array,这意味着array是指向DynamicArray<T>的指针。所以用

T t = array[currentPosition];

您告诉编译器返回位置DynamicArray<T>的{​​{1}}。您无法将其分配给array + currentPosition,因为t只是t而且实际上不是您想要的,因为指针只指向一个int

您需要的是取消引用指针然后访问元素,如

DynamicArray<T>

实际上你应该返回一个引用,这样你就可以修改那个元素,看起来像是

T t = (*array)[currentPosition];

答案 2 :(得分:0)

{
  "name": "ChatRoom",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "city": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "ChatMessagers": {
      "type": "hasMany",
      "model": "ChatMessager",
      "foreignKey": ""
    },
    "chatMessages": {
      "type": "hasMany",
      "model": "ChatMessage",
      "foreignKey": "messagesInChat"
    }
  },
  "acls": [],
  "methods": {}
}

是个问题,T t = array[currentPosition]; 的类型是array。因此,DynamicArray<T>*的类型为array[currentPosition]

这应该解决它:

DynamicArray<T>