Reputation: 137
I am working on a homework assignment that involved converting matrix and array classes supplied by my professor into templates. I am getting an error '=': cannot convert from 'Array *' to 'int' in my line m[i] = new Array < Type >(cols);
I would assume this is because m[i] is returning an int but I don't think it should be if I wrote my templates correctly and I can't quite figure out why it is giving back an int instead of a array pointer since m is an array of array pointers here is the code to my array template minus some overloads for << not used in this code.
template
< typename Type >
class Array
{
private:
int len;
Type * buf;
public:
Array(int newLen)
: len(newLen), buf(new Type[newLen])
{
}
Array(const Array & l)
: len(l.len), buf(new Type[l.len])
{
for (int i = 0; i < l.len; i++)
buf[i] = l.buf[i];
}
int length()
{
return len;
}
int & operator [] (int i)
{
assert(0 <= i && i < len);
return buf[i];
}
}
Here is my matrix template the error occurs in minus the same << overloads
#pragma once
#include "Array.h"
template
< typename Type >
class Matrix
{
private:
int rows, cols;
Array< Array<Type> * > m;
public:
Matrix(int newRows, int newCols)
: rows(newRows), cols(newCols), m(rows)
{
for (int i = 0; i < rows; i++)
m[i] = new Array < Type >(cols);
}
int numRows()
{
return rows;
}
int numCols()
{
return cols;
}
Array < Type > & operator [] (int row)
{
return *m[row];
}
}
Upvotes: 0
Views: 123
Reputation: 304102
The proximal issue is that Array
isn't fully templated:
int & operator [] (int i)
Indexing into an Array<T>
shouldn't give you an int&
, it should give you a T&
!
The other issue with your code is that you have a new
in your Array
constructor - where's the corresponding delete
? You're leaking memory!
Same for the Matrix
constructor, which additionally has the potential of double deleting memory if you happen to copy it.
See Rule of Three
Upvotes: 1
Reputation: 434
The [] operator overload in the array class is what's messing you up.
int & operator [] (int i)
{
assert(0 <= i && i < len);
return buf[i];
}
It clearly returns an int as its type and when you try to use it such that: m[i] = new Array < Type >(cols);
m[i] will return an int type which you're trying to assign a new Array to.
Upvotes: 2