Проблема с C ++ - PullRequest
       3

Проблема с C ++

1 голос
/ 16 января 2011

Для следующего кода:

#include <map>
#include <iostream>
#include <string>

using namespace std;

template <class T>
class Foo{
  public:
    map<int, T> reg;
    map<int, T>::iterator itr;

    void add(T  str, int num) {
      reg[num] = str;
    }

    void print() {
      for(itr = reg.begin(); itr != reg.end(); itr++) {
        cout << itr->first << " has a relationship with: ";
        cout << itr->second << endl;
      }
    }
};

int main() {
  Foo foo;
  Foo foo2;
  foo.add("bob", 10);
  foo2.add(13,10);
  foo.print();
  return 0;
}

Я получаю ошибку:

 type std::map<int, T, std::less<int>, std::allocator<std::pair<const int, T> > > is not derived from type Foo<T>

Я никогда не использовал шаблоны C ++ - что это значит?

1 Ответ

3 голосов
/ 16 января 2011

Вы пропускаете тип, когда объявляете экземпляры Foo.

В вашем случае вы бы хотели:

  Foo<std::string> foo;
  Foo<int> foo2;

Вам также необходимо добавить ключевое слово typename в строку:

    typename map<int, T>::iterator itr;

См. здесь , почему вам понадобится typename.

Edit, вот модифицированная версия вашего кода, которая компилируется и запускается локально:

#include <map>
#include <iostream>
#include <string>

using namespace std;

template <class T>
class Foo{
public:
    map<int, T> reg;
    typename map<int, T>::iterator itr;

    void add(T  str, int num) {
        reg[num] = str;
    }

    void print() {
        for(itr = reg.begin(); itr != reg.end(); itr++) {
            cout << itr->first << " has a relationship with: ";
            cout << itr->second << endl;
        }
    }
};

int main() {
    Foo<std::string> foo;
    Foo<int> foo2;
    foo.add("bob", 10);
    foo2.add(13,10);
    foo.print();
    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...