簡體   English   中英

在C ++中訪問靜態類變量?

[英]Accessing static class variables in C++?

重復:
C ++:對靜態類成員的未定義引用

如果我有這樣的班級/結構

// header file
class Foo
{
   public:
   static int bar;
   int baz;
   int adder();
};

// implementation
int Foo::adder()
{
   return baz + bar;
}

這行不通。 我收到“對Foo :: bar的未定義引用”錯誤。 如何在C ++中訪問靜態類變量?

您必須在實現文件中添加以下行:

int Foo::bar = you_initial_value_here;

這是必需的,因此編譯器有一個放置靜態變量的位置。

這是正確的語法,但是,必須在標頭之外單獨定義Foo::bar 在您的一個.cpp文件中,這樣說:

int Foo::bar = 0;  // or whatever value you want

您需要添加一行:

int Foo::bar;

那將定義您一個存儲。 類中static的定義類似於“ extern”-提供符號但不創建符號。

foo.h

class Foo {
    static int bar;
    int adder();
};

foo.cpp

int Foo::bar=0;
int Foo::adder() { ... }

要在類中使用靜態變量,首先必須給靜態變量(初始化)一個通用值(無局部值),然后才能訪問類中的靜態成員:

class Foo
{
   public:
   static int bar;
   int baz;
   int adder();
};

int Foo::bar = 0;
// implementation
int Foo::adder()
{
   return baz + bar;
}

暫無
暫無

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

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