簡體   English   中英

使用靜態成員變量初始化map

[英]initialize map with static member variable

我不明白為什么我不能在地圖的初始化列表中使用類的公共const靜態成員(可能是任何容器)。 據我所知,“MyClass :: A”是一個右值,看起來它應該與我使用“THING”的情況完全相同,它也是一個類外的靜態const。

這是錯誤:

Undefined symbols for architecture x86_64:
  "MyClass::A", referenced from:
      _main in map-380caf.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

以下是代碼:

#include <iostream>
#include <map>
#include <string>

static const int THING = 1;

class MyClass {
public:
    static const int A = 1;
};

int
main()
{
    int a;
    typedef std::map<int, std::string> MyMap;

    // compiles and works fine
    a = MyClass::A;
    std::cout << a << std::endl;

    // compiles and works fine
    MyMap other_map = { {THING, "foo"} };
    std::cout << other_map.size() << std::endl;

    // Does not compile
    MyMap my_map = { {MyClass::A, "foo"} };
    std::cout << my_map.size() << std::endl;

    return 0;
}

更新1:

在OS X上使用clang:

Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin14.5.0
Thread model: posix

編譯器標志:

clang++ map.cc -std=c++1y

地圖代碼中的某些內容可能試圖獲取對int的引用的地址。

這里的類定義:

class MyClass {
public:
    static const int A = 1;
};

實際上並沒有為A創建任何內存。 為了做到這一點,你必須在頭文件中做:

class MyClass {
public:
    static const int A;
};

並在CPP文件中:

const int MyClass::A = 1;

或者我想在最新的C ++版本中,您可以在標題中保留= 1 ,只需在CPP文件中聲明存儲:

const int MyClass::A;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM