c++ - 在 C++ 中,是否可以在构造函数中访问静态变量?

标签 c++ static constructor

我正在尝试:

class MyClass {
public:
    MyClass();

    int myID;
    static int currentID;
};

MyClass::MyClass() {
    myID = currentID;
    ++currentID;
}

我正在尝试为此类的所有实例分配一个唯一 ID。

编辑:

这对我不起作用。我在 xcode 中得到了其中两个:

undefined symbol : “GameObject::currentID”,引用自: GameObject.o 中的 __ZN10GameObject9currentIDE$non_lazy_ptr (也许你的意思是:__ZN10GameObject9currentIDE$non_lazy_ptr) ld:未找到符号 collect2: ld 返回 1 个退出状态

最佳答案

对我有用:

#include <iostream>

class My
{
    public:
    My() : id(++currentId) {}

    int id;
    static int currentId;
};

int My::currentId = 0;

std::ostream & operator<<(std::ostream & os, My & m)
{
    return os << m.id;
}

int main()
{
    My a;
    My b;
    My c;

    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
}

输出:

> ./x
1
2
3

关于c++ - 在 C++ 中,是否可以在构造函数中访问静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8367503/

相关文章:

c++ - 客户端断开连接后处理服务器应用程序中的线程

java - 为什么我不能使用静态上下文中的 "super"变量,即使 "super"指的是父类而不是类实例,这与 "this"不同?

C |静态数组: why does writing out-of-bounds not result in exception?

java - 如何处理防御性编程的各种情况?

c++ - 如何强制 ASan 显示不止一个调用堆栈行?

c++ - "undefined reference to ` QString::fromAscii_helper(char const*, int) '"

deployment - Nginx 位置、别名、重写、root

python - 带有可选参数的 Boost.Python 构造函数

android - 检查 Db 列数据

c++ - 奇怪 - mysql 的 sql::SQLException 未被其类型捕获,而是被捕获为 std::exception 并成功投回