码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 模板参数做容器参数,迭代器报错 vector<T>::const_iterator

时间:2014-10-25 22:51:55      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:blog   http   ar   使用   for   sp   数据   on   log   

错误如下:

template<class T>
void temp(std::vector<T>& container)
{
        std::vector<T>::const_iterator p; //error: expected ‘;’ before ‘p’
        for(p = container.begin(); p != container.end(); ++p)
        {
                //...
        }
}

 

解决方法:

std::vector<T>::const_iterator p; //error: expected ‘;’ before ‘p’

typename std::vector<T>::const_iterator p;

原因:
 1、首先类除了可以定义数据成员或函数成员之外,还可以定义类型成员。
 2、使用std::vector<T>::const_iterator时,编译器假定这样的名字指定的是数据成员,而不是数据类型成员。
 3、如果希望编译器将const_iterator当做类型,则必须显示告诉编译器这样做,这就是我们加typename的原因。

 

更深入理解可以看nested dependent name(嵌套依赖名字)


 本人以前的幼稚解决方法:

c++ 模板参数做容器参数,迭代器报错 vector<T>::const_iterator

c++ 模板参数做容器参数,迭代器报错 vector<T>::const_iterator

标签:blog   http   ar   使用   for   sp   数据   on   log   

原文地址:http://www.cnblogs.com/dongzhiquan/p/4050997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!