LINUX.ORG.RU

как правильно перегрузить оператор?


0

0

есть класс std::vector, реализация динамических массивов, хочется 
чтобы размер массива автоматически изменяелся при работе оператора [].

пишу:
#include <iostream>
#include <vector>

template<class T>
class myclass : public vector;
{
    int &operator[](unsigned num)
    {
        while(num > vector::size())
            vector::push_back(NULL);
        vector::push_back(num);
    }
};

int main()
{
    myclass v1;
}

при сборке получаю:
testvector.cpp:16: error: expected class-name before ';' token
testvector.cpp:16: error: expected `{' before ';' token
testvector.cpp:17: error: expected unqualified-id before '{' token
testvector.cpp: In function `int main()':
testvector.cpp:28: error: missing template arguments before "v1"
testvector.cpp:28: error: expected `;' before "v1"


как это правильно написать ?
anonymous

#include <iostream>
#include <vector>

template<class T>
class myclass : public vector<T>;
{
T &operator[](unsigned num)
{
if (size() < num)
resize(num);
return at(num);
}
};

int main()
{
myclass v1;
}

iDeveloper
()
Ответ на: комментарий от iDeveloper

#include <iostream> #include <vector>

using namespace std;

template<class T> class myclass: public vector<T> { public: T& operator[](size_t i) { resize(i); return vector<T>::operator[](i); } };

int main(int argc, char **argv) { myclass<int> v; v[12] = 32; cout << v[12] << endl;

return 0; }

iDeveloper
()
Ответ на: комментарий от iDeveloper

#include <iostream>
#include <vector>

using namespace std;

template<class T>
class myclass: public vector<T>
{
public:
T& operator[](size_t i)
{
resize(i);
return vector<T>::operator[](i);
}
};

int main(int argc, char **argv)
{
myclass<int> v;
v[12] = 32;
cout << v[12] << endl;

return 0;
}

Как меня достал етот TEX!!!

iDeveloper
()
Ответ на: комментарий от Legioner

Во первых данная функция вызывает не константную функцию resize(), во вторых возвращаемый результат может изменятся -> что оба const не нужны?

iDeveloper
()
Ответ на: комментарий от iDeveloper

Я бы написал для консистентности. Что то вроде

const T& operator[](size_t i) const
{ 
  if (i >= size())
    const_cast<myclass<T>*>(this)->resize(i); 
  return vector<T>::operator[](i); 
}

Legioner ★★★★★
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.