+ Reply to Thread
Results 1 to 3 of 3

Thread: How can I overload index ([]) operator in C++ class?

  1. #1

    How can I overload index ([]) operator in C++ class?

    How can I overload index ([]) operator in C++ class?

    I have a custom class and I want to have ability that class should return some value based on the index.

    Can I do this?

    Please help.

  2. #2
    You can use following example:

    Code:
    template <typename T, int SIZE>
    class CSubscript
    {
    private:
    	T m_T[SIZE] ;
    
    public:
    
    	T& operator [](const unsigned int nIndex)
    	{
    		return m_T[nIndex] ;
    	}
    
    } ;
    
    void Subscript()
    {
    	CSubscript<int, 5> objSubscript ;
    
    	for (int nIndex=0; nIndex<5; nIndex++)
    	{
    		objSubscript[nIndex] = nIndex * 2 ;
    	}
    
    	for (nIndex=0; nIndex<5; nIndex++)
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "Index %d : Value %d\n", nIndex, objSubscript[nIndex]) ;
    		OutputDebugString(szMessage) ;
    	}
    }
    Hope this helps.

  3. #3
    Really nice example.

    Thank you.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts