C++ hiba [megoldva]

Fórumok

Sziasztok!

A probléma az alábbi kódra adódik:

//==================main.cpp==================

#include <iostream>
#include "array.h"
#include <functional>
#include <list>
#include <deque>

template <class T>
class Less: public std::unary_function<T, bool>
{
  T x;
public:
  Less(const T& t):x(t) {}
  bool operator()(const T& t) const
  {
    return t<x;
  }
};

template <class T>
class Print
{
  T s;
public:
  Print():s(0) {}
  void operator()(const T& a)
  {
    std::cout << a << ' ';
    s+=a;
  }
  T get() const
  {
    return s;
  }

  ~Print()
  {
    std::cout << std::endl;
  }
};

int main()
{
  int yourMark = 1;

  Array<int, 5> ai;
  Array<double, 3> ad(2.0);
  const Array<char, 2> ac('a');
  if ('a' == ac.at(0))
    yourMark = ac.size();


  const Array<double, 3> cad = ad;
  ai[0] = ai[1] = ai[2] = 3;
  ai[3] = ai[4] = 1;
  const Array<int, 5> cai = ai;
  yourMark = cai[0];

}

//==================array.h==================

#ifndef ARRAY_H
#define ARRAY_H

#include <vector>

template<typename T, int x>
class Array
{
public:
    Array() {tomb.reserve(x);};
    Array(T e)
    {
        tomb.reserve(x);
        for(int i=0; i<x; i++)
        {
            tomb[i]=e;
        }
    }


    T at(int h) const
    {
        return tomb[h];
    }

    int size() const
    {
        return x;
    }

Array& operator=(const Array& sName)
{
    if ( this == &sName )
        return *this;
    Clear();
    CopyFrom( sName );
    return *this;
}

    void Clear()
    {
        for(int i=0; i<x; i++ )
        {
        tomb.pop_back();
        }
    }

    void CopyFrom( const Array& sName )
    {
        for(int i=0; i<sName.size(); i++)
        {
            this.push_back(sName[i]);
        }
    }
    T& operator[](int y) const { return tomb[y]; }
private:

    std::vector<T> tomb;
};


#endif

A hiba pedig ez:
array.h: In member function `T& Array::operator[](int) const [with T = int, int x = 5]':
main.cpp:53: instantiated from here
array.h:55: error: invalid initialization of reference of type 'int&' from expression of type 'const int'

Hozzászólások

Ja, és mégvalami. Tudom, hogy azzal van gondja hogy konstans a függvény és referenciával tér vissza, viszont ha nem konstans, akkor nem tudom lekérni konstans objektumom y-adik elemét, ha pedig nem referenciával térek vissza akkor pedig egy ilyen hibaüzenetet dob: main.cpp:53: error: non-lvalue in assignment , amivel nem tudok mit kezdeni!


T& operator[](int y) const { return tomb[y]; }

Itt a visszaeresi erteknek const T& -nek kene lennie, es kell egy nem const valtozat is. Csak nem gsd zh-jara gyakorolsz?