0

I want to override array index operator in my class. Here's what i am trying to do,but not succeeding.

class Complex{              
    Complex const& operator[](unsigned int) const; // Read-only access
    Complex& operator[](unsigned int);             // Read/Write access:
};

const Complex& Complex::operator [](unsigned int unsignedInt) const {
    const Complex* temp = this+i;
    return *temp;
}
Complex& Complex::operator [](unsigned int unsignedInt) {
    Complex* temp = this+i;
    return *temp;
}

EDIT : I want to do something like :

Complex **c = new Complex[5];    //Create 2D array
c[2] = new Complex();            //Initialize
cout<<*c[2];                     //print by overloading <<
6
  • 1
    What does that do? What's the problem with that code? Commented Feb 12, 2013 at 10:37
  • instead of Complex Complex::const& operator[], Complex const Complex::operator[] Commented Feb 12, 2013 at 10:37
  • What does it mean: you are not succeeding? Commented Feb 12, 2013 at 10:37
  • Also, in Complex& Complex::operator[], you cannot return a pointer as a reference. Return the actual object instead. Commented Feb 12, 2013 at 10:38
  • Ouch : const Complex* temp = this+i; In short, non-multisyllabic words, don't do this. Commented Feb 12, 2013 at 10:38

2 Answers 2

3

Your function definition syntax is wrong:

Complex Complex::const& operator[](unsigned int i) const{

The return type is supposed to be annotated by const&, and the explicit name qualification Complex:: belongs to the function name, operator[]:

Complex const& Complex::operator[](unsigned int i) const {

Furthermore, the implementation seems to be wrong:

const Complex* temp = this+i;
return *temp;

This doesn’t make a lot of sense. You probably mean something along these lines:

Complex temp = *this + i;
return temp;

Assuming an appropriate operator+ overload. Although it’s hard to say which semantics you really want here since there’s no intuitive indexed access for a Complex anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

I would like to create an array of pointers i.e. 2D array of Complex class by declaring my own new, delete and [] operaors.
2

Instead of

Complex Complex::const& operator[](unsigned int i) const

It should be

const Complex& Complex::operator[](unsigned int i) const

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.