3

以下代码在声明迭代器的行生成语法错误:

template <typename T>
class A
{
  public:

    struct B
    {
       int x, y, z;
    };

    void a()
    {
        std::map<int, B>::const_iterator itr; // error: ; expected before itr
    }

    std::vector<T> v;
    std::map<int, B> m;
};

这仅在 A 是模板类时发生。这段代码有什么问题?如果我将 B 从 A 中移出,则代码编译得很好。

4

1 回答 1

8

你需要一个类型名:

 typename std::map<int, B>::const_iterator itr;

迭代器是一个依赖类型(依赖于 B),当你遇到这种情况时,编译器会要求你用类型名来澄清它。

这里对这个问题进行了合理的讨论。

于 2009-03-19T09:03:12.997 回答