簡體   English   中英

"對靜態成員的未定義引用"

[英]Undefined reference to a static member

我正在使用交叉編譯器。 我的代碼是:

class WindowsTimer{
public:
  WindowsTimer(){
    _frequency.QuadPart = 0ull;
  } 
private:
  static LARGE_INTEGER _frequency;
};

我收到以下錯誤:

未定義對“WindowsTimer::_frequency”的引用

我也嘗試將其更改為

LARGE_INTEGER _frequency.QuadPart = 0ull;

或者

static LARGE_INTEGER _frequency.QuadPart = 0ull;

但我仍然遇到錯誤。

有誰知道為什么?

您需要在 .cpp 文件中定義_frequency<\/code> 。

IE

LARGE_INTEGER WindowsTimer::_frequency;

使用 C++17,您可以聲明變量inline ,不再需要在 cpp 文件中定義它。

inline static LARGE_INTEGER _frequency;

鏈接器不知道在哪里為_frequency分配數據,您必須手動告訴它。 您可以通過簡單地添加以下行來實現此目的: LARGE_INTEGER WindowsTimer::_frequency = 0; 進入您的 C++ 源代碼之一。

更詳細的解釋在這里

如果在類中聲明了一個靜態變量,那么您應該像這樣在 cpp 文件中定義它

LARGE_INTEGER WindowsTimer::_frequency = 0;

這是另一個問題<\/a>的完整代碼示例,確實是這個問題的副本。

#include <iostream>

#include <vector>
using namespace std;

class Car
{

public:
    static int b;                   // DECLARATION of a static member


    static char* x1(int x)
    {
        b = x;                      // The static member is used "not as a constant value"
                                    //  (it is said ODR used): definition required
        return (char*)"done";
    }

};

int Car::b;                         // DEFINITION of the static 

int main()
{
    char* ret = Car::x1(42);
    for (int x = 0; x < 4; x++)
    {
        cout << ret[x] << endl;
    }

    return 0;
}

暫無
暫無

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

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