c++ - 在类本身中存储类的对象

标签 c++

如何在类本身中存储类的对象?

我知道我必须使用 static 关键字来完成我想要的。因此类应该看起来像:

class my_class {
public:
    static my_class instance;
    my_class() {
        my_class::instance = this
    }
};

下面是类中出现的确切代码

namespace ArmISA {
    class ISA {
        protected:
            static ISA* isa;
            MiscReg miscRegs[NumMiscRegs];
            const IntRegIndex *intRegMap;
            .....
        public:
            ISA() {
                ISA::isa = this;
                ...
            }
        ...
    };
}

我得到的错误是:

error: could not convert 'ArmISA::ISA::isa' from 'ArmISA::ISA*' to 'ArmISA::ISA'

最佳答案

my_class::instance = *this; 会起作用,但我希望您知道每次创建该类的新实例时,您的 instance 成员将被覆盖。此外,这意味着 instance*this 的拷贝而不是引用 - 对一个的更改对另一个不可见。

另一种选择是将 instance 声明为指针,在这种情况下,两个指针都指向同一个对象,然后 instance = this; 将编译:

static my_class* instance;

但是,我不确定您到底想达到什么目的。

关于c++ - 在类本身中存储类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15913653/

相关文章:

c++ - 在循环外存储 C++ 数组

C++ - 使用 'i' 检查 for 循环中的不同变量

c++ - 我可以使用 Visual Studio 201 0's C++ compiler with Visual Studio 2008' s C++ 运行时库吗?

c++ - 抑制下载速度的变化

c++ - 为什么我可以在 C 中调用函数而不声明它,但不能在 C++ 中调用?

c++ - std::function 参数类型

c++ - 线程安全和 `const`

c++ - 错误 : no matching function for call to 'TNode<Student>::TNode<const Student&)'

c++ - 确定跨域 Active Directory 组成员身份

c++ - 从包含 IP header 片段的二进制文件中读取结构的最佳方法是什么?