【问题标题】:How to access and initialize std::list from a class如何从一个类访问和初始化 std::list
【发布时间】:2016-05-26 17:54:18
【问题描述】:

我的问题可能很愚蠢,但我遇到了以下问题。

以下代码可以正常工作。我有全局或本地列表,可以正确实例化和推送值。

class THistory
{
public:
    UInt32          index;
    UInt32          navToID;
};

//Works Fine
class ML{
    public:
    static THistory *hist2;
};

main.cpp;
ML::hist2 = new THistory[HISTORY_BUFFER_SIZE];//global
std::list<THistory> histList;//global

histList.push_back(ML::hist2[0]);//inside main()

当我在类中移动列表时,问题就开始了。

//Problem


class ML{
    public:
    static THistory *hist2;
    static std::list<THistory> histList; //replace global list and put it inside ML class as static

}
main.cpp;
ML::hist2 = new THistory[HISTORY_BUFFER_SIZE];//global as before
////// Where to initialize the list?

ML::histList.push_back(CoreML::hist2[0]); //inside main() 
//LINK Error Undefined symbol

错误 LNK2001:未解析的外部符号“公共:静态类 std::list > CoreML::histList”(?histList@CoreML@@2V?$list@VTHistory@@V?$allocator@VTHistory@@@std@ @@std@@A)

我不知道如何初始化列表。任何指针都会有所帮助。

【问题讨论】:

标签: c++ list class initialization


【解决方案1】:

在类定义中只声明静态数据成员。您必须在类定义之外定义它们。例如

class ML{
    public:
    static THistory *hist2;
    static std::list<THistory> histList; //replace global list and put it inside ML class as static

};
^^^

// before the function main

std::list<THistory> ML::histList;

【讨论】:

    【解决方案2】:

    在 C++ 中,如果您在类中声明静态成员变量,则需要将该变量的定义放在某处。你得到的链接器错误是因为你已经声明了这个变量,但是你还没有定义它。

    在您程序的一个 C++ 源文件中,添加以下行:

    std::list<THistory> CoreML::histList; // Define the variable.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 2013-07-25
      相关资源
      最近更新 更多