C ++嵌套类(使朋友成为外部成员函数)?

时间:2018-11-22 22:11:40

标签: c++ class nested friend

我的代码:

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类中的访问私有成员无效。为什么朋友的陈述不起作用?

1 个答案:

答案 0 :(得分:1)

问题

必须先声明成员函数,然后才能friendfriend具有针对数据类型的内置前向声明,但不适用于该数据类型的成员。

解决方案

我个人同意Eljay的评论,将所有内容放在ControllerMetals public中,因为Controller已经将其隐藏了,但是如果作业说不,请做您必须通过的事情课程。

简单的解决方案:

friend整个Controller类来获取成员,但这可能太广泛了。

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

更多内容,以便在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;


};
相关问题