class template error

This is a discussion on class template error within the C++ Programming forums, part of the General Programming Boards category; I have created a class template that acts like an array. However, every time I try to set one of ...

  1. #1
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    902

    class template error

    I have created a class template that acts like an array. However, every time I try to set one of it's values, I get an error: example:
    ArrayTypeIDeclared[12] = Somevalue;

    yeilds:

    error C2106: '=' : left operand must be l-value.

    Here is the code to the template:
    Code:
    template <class T>
    class array
    {
    public:
    	array(int size)
    	{
    		Data = new T[size];
    		for(int x = 0; x < size; x++)
    			Data[x] = 0x0;
    	}
    
    	~array()
    	{
    		delete [] Data;
    	}
    
    	T* Data;
    
    	T operator [] (int index)
    	{
    		return Data[index];
    	}
    	
    };

  2. #2
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    801
    Try returning a reference from your subscript overload.

    Code:
    T& operator [] (int index)
    {
    return Data[index];
    }

  3. #3
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    902
    Aha!!! I love you.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  4. #4
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    801
    No problem. Just so you know what you were actually doing wrong, your original code was returning a copy of the value stored in the array at the position. This is ok for read access but if you want to write to this position then you need to return a reference to a memory location to be written to. That's what the '&' is for.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Testing some code, lots of errors...
    By Sparrowhawk in forum C Programming
    Replies: 48
    Last Post: 12-15-2008, 03:09 AM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. How to monitor process creation?
    By markiz in forum Windows Programming
    Replies: 31
    Last Post: 03-17-2008, 02:39 PM
  4. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 09:43 AM
  5. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21