簡體   English   中英

無法在 c++ 中初始化 static 成員

[英]Can't initialize static member in c++

當我運行代碼(第一個程序)時,它顯示var是私有成員的錯誤。我定義它是 static 成員,因此不應在 class 之外初始化var

#include <iostream>
using namespace std;

class example{
    private:
      static int var;
    public:
      example(){
          cout<< "exp is called"<< endl;
      };

};

int example::var =6;

int main(void)
{
    example exp1;
    cout<< exp1.var<<endl;
    exp1.var=5;
    example exp2;
    cout<< exp2.var<<endl;
    cout<< example::var<<endl;

    return 0;
}

但是此代碼成功運行;

#include <iostream>
using namespace std;
class MyClass{
   private:
      static int st_var;
   public:
      MyClass(){
         st_var++; //increase the value of st_var when new object is created
      }
      static int getStaticVar() {
         return st_var;
      }
};
int MyClass::st_var = 0; //initializing the static int
main() {
   MyClass ob1, ob2, ob3; //three objects are created
   cout << "Number of objects: " << MyClass::getStaticVar();
}

代碼有什么問題(第一個程序)?

var是一個私有成員變量。 無法從 class 外部訪問或查看它。 只有 class 和好友函數可以訪問私有成員。

您可以執行的訪問它的選項之一是添加一個返回其值的公共方法。

class example {
private:
    static int var;

public:
    example() {
        cout << "exp is called" << endl;
    }
    int getVar() {
        return var;
    }
};

並從 main 中調用它,如下所示:

cout << exp1.getVar() << endl;

static 數據成員的初始化沒有問題。 問題是您正在嘗試訪問 class 之外的私有成員。

您需要添加gettersetter才能訪問私有數據成員。

演示

提示:如果您使用的是 c++17,您可以使用inline變量來初始化 static 數據成員。

class Foo {
 private:
  inline static int x{};

 public:
  Foo() = default;
};

暫無
暫無

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

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