2

I know that this question has been asked before, and I red all the answers but I didn't find something that helped me. Hopefully you can ! So, I have a class named Vecteur which has two attributes: dimension (size of the table) and the table of values. And in the copy constructor when I try to copy the values of the Vecteur &v to the values of 'this' it gives me an error, and I don't know why because I think that I overloaded the [] operator ! (When I was trying to figure it out I put this->t[i] = v.t[i] and it worked ! but i found it weird because t is private).

Vecteur.h

#ifndef VECTEUR_H
#define VECTEUR_H
#include "typedef.h"

class Vecteur
{
    public:
        Vecteur(int);
        Vecteur(const Vecteur&);
        ~Vecteur();
        scal& operator[](int);
    protected:
    private:
        int dim;
        scal *t;
};

#endif // VECTEUR_H

Vecteur.cpp

#include "Vecteur.h"
#include "typedef.h"

Vecteur::Vecteur(int dim)
{
    this->dim = dim;
    t = new scal[dim];
}

Vecteur::~Vecteur()
{
    delete[] t;
}

Vecteur::Vecteur(const Vecteur &v)
{
    for(int i=0; i<dim; i++){
        t[i] = v[i];//The error
    }
}

scal& Vecteur::operator[](int i){
    return t[i];
}
Chandler Bing
  • 1,036
  • 2
  • 8
  • 14
  • You have defined this: scal& Vecteur::operator[](int i){ return t[i]; } now you have to define the `const` flavour of your operator, like this const scal& Vecteur::operator[](int i) const { return t[i]; } otherwise you're violating the contract. – Jean-François Fabre Oct 31 '16 at 21:04
  • @Jean-FrançoisFabre Which contract I'm violating? – Chandler Bing Oct 31 '16 at 21:09
  • `const Vecteur &v` is constant. You cannot call a non-constant method on it. – Jean-François Fabre Oct 31 '16 at 21:13
  • @Jean-FrançoisFabre Yes I tried to do that but it does not work ! In the header file I wrote: scal& operator[](int) const; And in the source file I wrote: scal& Vecteur::operator[](int i)const{ return t[i]; } Is the syntax correct? – Chandler Bing Oct 31 '16 at 21:45
  • `const scal& Vecteur`. There are 2 "const". – Jean-François Fabre Oct 31 '16 at 21:46
  • @Jean-FrançoisFabre Did that too and it gives me error: prototype for ‘const scal& Vecteur::operator[](int) const’ does not match any in class ‘Vecteur’ I really don't know why, and I spent lot of time trying to figure this out – Chandler Bing Oct 31 '16 at 21:48
  • of course you need to define it in your class as well. I'd do it only in the class (inline) and would drop it in cpp (else you cannot use a template): in your class `const scal& operator[](int) const;` – Jean-François Fabre Oct 31 '16 at 21:52

0 Answers0