首页 > 解决方案 > 静态成员变量只能在类的静态方法中使用,但为什么我们可以在 C++ 类的构造函数中为静态变量赋值呢?

问题描述

#include <iostream>
using namespace std;
 
class Player
{
private:
    static int next_id;
public:
    static int getID() { return next_id; }
    Player(int x) { **next_id = x;** }
};

int Player::next_id = 0;
 
int main()
{
  Player p1(1);
  cout << p1.getID() << " ";
  Player p2(2);
  cout << p2.getID() << " ";
  Player p3(3);
  cout << p3.getID();
  return 0;
}

构造函数不是静态函数,即使我们可以为静态变量赋值。在这里我们应该得到编译错误。但它运行良好,输出低于。输出:1 2 3

标签: c++constructorstatic

解决方案


#include <iostream>
using namespace std;

class Player
{
private:
    inline static int next_id;
public:
    static int getID() { return next_id; }
    Player(int x) { next_id = x; }
};



int main()
{
  Player p1(1);
  cout << p1.getID() << " ";
  Player p2(2);
  cout << p2.getID() << " ";
  Player p3(3);
  cout << p3.getID();
  return 0;
}

添加内联。


推荐阅读