c++ - 静态成员变量只能在类的静态方法中使用,但为什么我们可以在 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
解决方案
#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;
}
添加内联。
推荐阅读
- python - 为什么 python 允许我使用保留关键字创建变量?
- postgresql - 在 EC2 上使用 docker-compose up 对用户“postgres”进行密码身份验证失败
- facebook-javascript-sdk - Facebook登录:没有重定向,弹出窗口中的白页
- javascript - react-select 输入在我可以(鼠标单击)选择一个选项之前关闭
- algorithm - 使用重复减法的整数除法算法 - Off by One Errors
- django - 角度保存()方法不起作用英雄教程
- sql - SQL Server 触发器中的条件检查
- amazon-web-services - 从 serverless.yml 创建 AWS Cognito 用户池
- c - 返回函数指针数组
- minikube - 我在哪里可以找到部署在 minikube 中的应用程序的主机 IP 地址