麻烦朋友:如何授予私人访问内部类?

时间:2016-02-22 21:48:47

标签: c++ inner-classes friend

这里我有一个我一直在研究的链表实现的简化版本。我想将组件元素(节点)的计数保留为私有成员,然后让Component构造函数和析构函数完全处理变量count

但是,我收到编译器错误(VS2015)不允许我count中的任何成员函数(包括构造函数和析构函数)访问Component

' count':未声明的标识符

为什么friend声明在这种情况下不授予该访问权限?

class Outer {
private:
    class Component;
    friend class Component;
public:
    Outer() : count(0) {}
    unsigned int size() {
        return count;
    }
    void methodThatCreatesComponents() {
        entryPoint = new Component(nullptr);
        // I don't want to have to write ++count; every time I construct
    }
    void methodThatDeletesComponents() {
        delete entryPoint;
        // I don't want to have to write --count; every time I delete
        entryPoint = nullptr;
    }
private:
    unsigned int count;
    Component* entryPoint;
    class Component {
    public:
        Component(Component* next) {
            ++count;
        }
        ~Component() {
            --count;
        }
    private:
        Component* next;
    };
};

3 个答案:

答案 0 :(得分:0)

您需要使count符合适当的范围。

我猜测count应该是static的{​​{1}}成员。然后,你使用:

Outer

如果Component(Component* next) { ++Outer::count; } ~Component() { --Outer::count; } 应该是count的非static成员,则Outer需要Component的实例才能访问Object {1}}成员变量。

答案 1 :(得分:0)

您必须通过指向外部类的指针来访问外部类的私有成员。编译器错误与访问级别无关,它们可能表示类似"计数未在范围内声明"。

以下内容应解决问题:

class Component {
public:
    Component(Outer* outer, Component* next) : outer(outer) {
        ++outer->count;
    }
    ~Component() {
        --outer->count;
    }
private:
    Outer* outer;
    Component* next;
};

P.S。还有一种通过offsetof获取指向外部类的指针的hacky方法:

class Component {
public:
    Component(Component* next) : outer(outer) {
        ++outer()->count;
    }
    ~Component() {
        --outer()->count;
    }
private:
    Outer* outer() {
        return (void*)this - offsetof(Outer, entryPoint);
    }

    Outer* outer;
    Component* next;
};

答案 2 :(得分:0)

好吧我认为我提出了一个合适的方法,可以解决Component无法知道Outer内部this实例而不存储class Outer { private: class Component; public: Outer() : count(0) {} unsigned int size() { return count; } void methodThatCreatesComponents() { // other functionality entryPoint = createComponent(nullptr); } void methodThatDeletesComponents() { // other functionality deleteComponent(entryPoint); } private: unsigned int count; Component* entryPoint; class Component { public: Component(Component* next) : next(next) {} ~Component() {} private: Component* next; }; Component* createComponent(Component* next) { ++count; return new Component(next); } void deleteComponent(Component*& toDelete) { --count; delete toDelete; toDelete = nullptr; } }; 的事实对于每个实例。使用辅助函数:

this

这样我就不用担心每次构造或销毁时都会修改计数,或者是RbConfig::CONFIG['host']或其他旨在破坏嵌套对象结构的结构。其他答案肯定帮助我看到了我对内部阶级的看法出了什么问题。侨!