templates problems give compile error

T

Tony Johansson

Hello Experts!

Why do I get compile error here in this small class template. The compiler
error give this error
c:\Documents and Settings\Tony\kau\cplusplus\test12\start.cpp(9): error
C2440: '=' : cannot convert from 'int *' to 'int'

It's something that I have forgot in the class template..

#include <iostream>
template<typename T, int size>
class Array
{
public:
const int& operator[](int pos) const { return value[pos]; }
int& operator[](int pos) { return value[pos]; }
private:
T value[size];
};

#include <iostream>
#include "array.h"
using namespace std;
int main()
{
Array<int*,1> array1, array2;
array1[0] = new int(3);
return 0;
}

Many thanks

//Tony
 
C

cipherpunk

I'm not sure if this is a homework problem or not, so my answer will be
deliberately vague hint--but quite useful, for all that.

What is operator[] returning?

Once you figure it out (and remove the unused array2 which you're not
using), it compiles and runs cleanly under g++ using -Wall -W -ansi
-pedantic.

You should also make it a point to delete your pointer when you're done
using it. If you're going to manually allocate memory, you need to get
in the habit of taking responsibility for deallocating it when you're
done with it.
 
I

Ian

Tony said:
Hello Experts!

Why do I get compile error here in this small class template. The compiler
error give this error
c:\Documents and Settings\Tony\kau\cplusplus\test12\start.cpp(9): error
C2440: '=' : cannot convert from 'int *' to 'int'

It's something that I have forgot in the class template..

#include <iostream>
template<typename T, int size>
class Array
{
public:
const int& operator[](int pos) const { return value[pos]; }
So if T is int*, you are attempting to return an int* form a function
that returns an int&.

Should it be T&?

Ian
 
R

ravinderthakur

the problem lies in the statement::

array1[0] = new int(3);

on the data type level this will evalueate to

int = int*; //since array1[0] returns an int rather than int *

so this is giving the error message!!!


thanks
rt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top