【问题标题】:How can I access a class function in an iterator?如何访问迭代器中的类函数?
【发布时间】:2012-01-11 15:50:35
【问题描述】:

我有一堂课:

class Foo
{
  std::string name_;

  Foo(std::string name)
  {
    name_ = name;
  }

  std::string getName()
  {
    return name_;
  }
}

然后我有这些类的填充向量:

std::vector<Foo *> bar_;
/* ... populate bar_ ... */
std::vector<Foo *>::iterator iter = bar_.begin();

while(iter != bar_.end())
{
  std::cout << "Name: " << (*iter)->getName() << std::endl;
}

我的 (*iter)->getName() 不工作,我得到这个错误:

error: invalid cast from type ‘__gnu_cxx::__normal_iterator

【问题讨论】:

  • 你能发布完整的错误信息吗?顺便说一句,如果这不是您实际拥有的,请不要说您拥有“这些类的向量”。您的代码看起来正确;错误可能在其他地方。
  • 请注意,这是一个无限循环,因为iter 永远不会增加。不确定这是否是实际代码,因为 Foo 类定义中缺少分号。
  • 对于一个表现不佳的问题,我暂时给它一个-1。如果你清理它并发布真实代码,我会重新考虑。
  • @Grammin:您没有发布您正在编译的实际代码。您发布的代码中有几个错误,但不是您提到的那个。请发布实际代码。
  • 如果您确实要编译代码,请注意您的循环将是无限的,因为您永远不会递增 iter...

标签: c++ vector iterator


【解决方案1】:
  1. 将成员设为公开
  2. 接下来,如果迭代器是 const_iterator(或容器是 const,或两者兼有),则将成员设为 const

所以

struct Foo
{
  std::string getName() const  { /* ... */ }
};

class Foo
{
 public:
  std::string getName() const { /* ... */ }
};

【讨论】:

  • 但迭代器不是 const。此外,鉴于 OP 在构建类之前没有问题,访问问题似乎不是这个(诚然呈现不佳)问题的原因。
猜你喜欢
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 2017-08-22
相关资源
最近更新 更多