"未定义"在C ++中引用类成员 [英] "Undefined" reference to class member in C++

查看:193
本文介绍了"未定义"在C ++中引用类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在链接此代码时:

While linking this code:

#include <map>
using std::map;
#include <string>
using std::string;
class C {
public:
    static void dump() {
        for (const auto& e : data) {
            string(e.first);
        }
    }
private:
    static map<string,map<string,string>> data;
};
int main() {
    C::dump();
}

...我得到这个错误:

... I get this error:

/tmp/cc4W2iNa.o: In function `C::dump()':
test.cpp:(.text._ZN1C4dumpEv[_ZN1C4dumpEv]+0x9): undefined reference to `C::data'
collect2: error: ld returned 1 exit status

...来自g ++(GCC)4.9.1。
我做错了什么?

... from g++ (GCC) 4.9.1. Am I doing anything wrong?

推荐答案

您声明了 C :: data ,但没有定义它。在类的外部添加一个定义:

You've declared C::data, but not defined it. Add a definition outside the class:

map<string,map<string,string>> C::data;

在一个包含多个源文件的较大程序中,这只需要一个源文件即可满足一个定义规则;而类定义(包括 data 的声明)可以放在头中,以便在需要的地方提供。

In a larger program, which more than one source file, this must go in just one source file to satisfy the One Definition Rule; while the class definition (including the declaration of data) might go in a header to be available wherever it's needed.

这篇关于&QUOT;未定义&QUOT;在C ++中引用类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆