【问题标题】:How to use iterator of static stl list?如何使用静态 stl 列表的迭代器?
【发布时间】:2014-02-24 12:05:35
【问题描述】:

我是 C++ 新手。

在我的程序中,我应该有一些“全局”列表(应该只初始化一次)和一个函数(两者都应该可以从其他类和文件中访问)。我是这样定义的:

//header.h file    
#include <list>    
using namespace std;

class ClassA {
public:
    int Var;
};

class StaticListAndFunc {
    static list<ClassA> StaticListOfClassA;
    static return_t StaticFunc(int x, int y);
};

我的静态函数应该使用 StaticListOfClassA 和其他一些简单的输入。 现在我正在尝试使用 StaticListOfClassA 在源文件中实现 StaticFunc:

//source.cpp
  #include "header.h"  
   return_t StaticListAndFunc::StaticFunc(int x, int y) {
        list<ClassA>::iterator TheIterator = StaticListOfClassA.begin();
        ...
};

我遇到的错误:“source.cpp: undefined reference to `ClassA::StaticListOfClassA'”(在 list::iterator TheIterator = StaticListOfClassA.begin(); 行中)

我应该如何定义迭代器?或者也许还有另一种更好的方法来定义一个以后可以从其他文件和类轻松访问的类? 我真的很感谢任何帮助..

【问题讨论】:

  • 你的 link 错误,而不是编译时错误。你从来没有定义你的类静态变量,你只是声明了它。它需要在某个翻译单位的某个地方有个家。对我来说,该功能正上方看起来像是一个美味的地方。
  • In my program I should have some 'global' list (that should initialized only once) 为什么?

标签: c++ list stl static iterator


【解决方案1】:

问题是您没有定义静态列表。在 source.cpp 模块中你应该写

list<ClassA> StaticListAndFunc::StaticListOfClassA;

也就是说你需要定义这个静态数据成员。

还要考虑到您将函数 StaticFunc 声明为具有私有访问控制。您不能在类成员函数或友元函数之外调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 2012-11-05
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多