How to solve thie error "error C2440: '=' : cannot convert from 'DynamicArray<T> *' to 'int *'" ?
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include<iostream>
using namespace std;
#include"DynamicArray.h"
int main()
{
DynamicArray<int> da(2);
DynamicArray<int> db(2);
DynamicArray<DynamicArray<int>> array_of_arrays(2);
array_of_arrays[0] = da;
array_of_arrays[1] = db;
da[0] = 5;
da[1] = 2;
db[0] = 3;
db[1] = 4;
cout << array_of_arrays[0][0] << endl;
return 0;
}
|
DynamicArray.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
#ifndef DYNAMICARRAY_H_
#define DYNAMICARRAY_H_
template <class T>
class DynamicArray {
private:
int _size;
int *ptr;
T _elements;
public:
DynamicArray() {
_elements=0;
_size = 8;
ptr = new T[_size];
for(int i=0; i<_size; i++)
ptr[i] = 0;
}
DynamicArray(DynamicArray &a) {
_size = a._size;
ptr = new T[_size];
for(int i=0; i<_size; i++)
ptr[i] = *a.ptr[i];
}
DynamicArray(int size) {
_size = size;
ptr = new T[_size];
for(int i=0; i<_size; i++)
ptr[i]=0;
}
void addElement(int element) {
if(_elements>=_size)
{
T *temp;
temp = new T[_size+1];
for(int i=0; i<_size; i++)
temp[i] = ptr[i];
_size+1;
delete []ptr;
ptr = temp;
}
ptr[_elements] = element;
_elements++;
}
int getElement(unsigned int index) const {
return ptr[index];
}
void setElement(unsigned int index, int element) {
if(index >= _size)
{
T *temp;
temp = new T[index+1];
for(int i=0; i<_size; i++)
temp[i] = ptr[i];
for(int i=_size; i<=index; i++)
temp[i] = 0;
_size+1;
delete []ptr;
ptr = temp;
}
ptr[index] = element;
}
T& operator[] (int index) {
return ptr[index];
}
DynamicArray& operator= (DynamicArray &right) {
DynamicArray temp(right);
_size = right._size;
ptr = temp.ptr;
_elements = right._elements;
return *this;
}
};
#endif DYNAMICARRAY_H_
|
Error happens at the bold texts... (line 28)
I don't understand why there is this error although, i use the same syntax in the previous constructor.
How to solve this and what is the cause of this problem?
Thank you very much :))
Last edited on
You are assigning a T* to int*. On line 10 (of main) you have an object with T = DynamicArray<int>. Hence the error.
Can I take it that _elemements is the number of elements allocated and ptr is the allocated block?
If so, the types are wrong. Take another look, I'm sure you'll work it out.
You have ptr as int but in array_of_arrays ptr is DynamicArray<int> not just int.
I changed int *ptr to `T *ptr' on line 8
I changed operator= to this:
1 2 3 4 5 6
|
DynamicArray& operator= (const DynamicArray &right) {
_size = right._size;
ptr = right.ptr;
_elements = right._elements;
return *this;
}
|
With these 2 changes it compiled and ran:
1 2 3 4
|
5
Process returned 0 (0x0) execution time : 0.062 s
Press any key to continue.
|
Topic archived. No new replies allowed.