C++、内部类以及为什么只能将成员创建为指向它们的指针

标签 c++ inner-classes

为什么只能创建内部类的指针作为封闭类的成员。 它在内存中是如何排列的,为什么它会阻止这种情况,例如:

class temp  
{  
    public:

    class inner
    {
    public:
        inner(int a = 0) : memberInt(a) {}
        const int memberInt;
    };

    temp(int i = 0) : member(i)  
    {  
    }  
    inner *i; // this works  
    inner i; // this doesn't  
    int member;  
};  

提前致谢:-)。

最佳答案

假设我将第二个代码(内部 i)重命名为内部 i2,上面的代码实际上在 g++ 中编译得很好。

这是我用 g++ 编译的确切代码:

class temp  
{  
    public:

    class inner
    {
    public:
        inner(int a = 0) : memberInt(a) {}
        const int memberInt;
    };

    temp(int i = 0) : member(i)  
    {  
    }  

    inner *i;
    inner i2;
    int member;  
}; 


int main()
{
    return 0;
}

关于C++、内部类以及为什么只能将成员创建为指向它们的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5767986/

相关文章:

c++ - 在字符串范围列表中搜索字符串

c++ - 从 C++ 中继承的虚拟模板类返回内部类

c++ - 使用 SSE 内在函数存储四个 16 位整数

c++ - C++ 中的 Vector2 类

c++ - 嵌套类的类内 friend 是否可以访问外部类成员?

scala - 使用内部类作为类型参数

reactjs - 功能组件嵌套 vs. props

java - 从匿名内部类访问外部类的 this,其中外部类具有泛型

c++ - 在 OpenGL 中显示立方体的问题

c++ - 使用 clCreateEventFromGLsyncKHR 扩展函数时出现链接错误