【问题标题】:Static members variables can be used only in static methods of class, but why we can assign value to static variable inside constructor of C++ class?静态成员变量只能在类的静态方法中使用,但是为什么我们可以在 C++ 类的构造函数中为静态变量赋值呢?
【发布时间】:2021-01-20 09:56:06
【问题描述】:
#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

【问题讨论】:

  • “静态成员变量只能在类的静态方法中使用”你在哪里读到的?
  • 注意**不能用于代码格式化,使用注释来突出部分代码
  • @Pankaj Kumar 如果您删除“仅”这个词,您的问题的标题将或多或少是正确的。:)
  • 我认为您将此与非静态成员变量只能用于非静态成员函数的方式混淆了。静态成员变量的重点是它们在所有实例之间共享。

标签: c++ constructor static


【解决方案1】:
#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;
}

添加内联。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多