C++ Nested class (Make friend outer member function)?

C++ Nested class (Make friend outer member function)?

我的代码:

class Controller {

private:
    class ControllerMetals {
        private:
            int m_size;
            Metals * m_metals;
        public:
            ControllerMetals();
            Metals & getMetals() const;
            int getSize() const;
            void setSize(int size) { m_size = size; }
            void init();
            void show();
            void erase();
        friend void Controller::start(ControllerMetals & c); // why don't work ?
    };

private:
     ControllerMetals * controlMetals;

public:
    void start(ControllerMetals & c);
    ControllerMetals * getControlMetals() const;
    Controller();

};

我想做一个无效的开始来访问 ControllerMetals 中的私有成员 class。为什么朋友声明不起作用?

问题

成员函数必须先声明,然后才能friend它们。 friend 有一个数据类型的内置前向声明,但没有该数据类型的成员。

解决方案

我个人同意 Eljay 的评论,将所有内容都放在 ControllerMetals public 中,因为它已经被 Controller 隐藏了,但是如果作业拒绝,请执行您必须执行的操作通过课程。

简单的解决方案:

friend整个Controllerclass来获取会员,但是这可能太宽泛了。

更复杂、更细粒度的解决方案:

更多内容以便在 ControllerMetals 之前声明所需的成员函数。你可以摆脱这个,因为 start 只需要一个 ControllerMetals 的声明来引用它。

class Controller {

    class ControllerMetals; // forward declare to make available for referencing
public:
    void start(ControllerMetals & c); // start now known. Can friend
    ControllerMetals * getControlMetals() const;
    Controller();

private:
    // now we can fully define ControllerMetals
    class ControllerMetals {
        private:
            int m_size;
            Metals * m_metals;
        public:
            ControllerMetals();
            Metals & getMetals() const;
            int getSize() const;
            void setSize(int size) { m_size = size; }
            void init(); // why is this not done in the constructor?
            void show();
            void erase();
        friend void Controller::start(ControllerMetals & c); // now works
    };
     ControllerMetals * controlMetals;


};