簡體   English   中英

靜態const int成員和未定義的引用

[英]static const int member and undefined reference

我將gcc 4.7.3用於ARM平台來編譯我的代碼。 我有幾個這樣的課程:

// types.h
enum Types
{
    kType1,
    kType2
    // ...
};

// d1.h
class D1 : public Base
{
public:
    static const int type = kType1;
    // ...
};

// d2.h
class D2 : public Base
{
public:
    static const int type = kType2;
    // ...
};

在某些地方,我使用了這些類:

MyObject obj;
doSomething<D1>(obj);
doSomething<D2>(obj);

// other.cpp
class Foo
{
    template<typename T>
    void doSomething(MyObject obj)
    {
        mm_.insert(std::multimap<int, MyObject>::value_type(T::type, obj));
    }
};

並獲取下一條消息(在鏈接期間):

undefined reference to `D1::kType`
undefined reference to `D2::kType`
// more messages of this type

好。 如果我像這樣更改do_something函數:

template<typename T>
void doSomething(MyObject obj)
{
    mm_.insert(std::multimap<int, MyObject>::value_type( (int) T::type, obj));
}

它可以編譯。 但為什么? 在標准中找不到任何相關內容。 有人對發生的事情有想法嗎?

謝謝。

PS

此修復

 // d1.cpp
 const int D1::kType;

也可以,但這是預期的。

PPS在使用對T :: type的引用或指針的情況下,答案將非常明顯,但是我看不到任何需要ref或ptr的東西。 AFAIK std :: multimap :: value_type按值(而不是ref或ptr)接受參數。

// d1.cpp
const int D1::kType;

// d2.cpp
const int D2::kType;

答案是,

//d1.h
public:
    static const int type = kType1;

就像函數原型一樣,它被編譯到包含標頭的每個復雜對象(cpp文件)中,因此由於ODR規則,它實際上並沒有保留內存空間,否則鏈接器會找到許多實例。每個包含標題的編譯單元中的變量。

因此,您需要一個編譯單元(一個cpp文件),該單元定義將用於多次使用的標頭中的類常量的實際內存空間。

暫無
暫無

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

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