【问题标题】:C++ Nested class (Make friend outer member function)?C ++嵌套类(交朋友外部成员函数)?
【发布时间】:2018-11-22 22:11:39
【问题描述】:

我的代码:

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();

};

我想让一个 void 开始访问 ControllerMetals 类中的私有成员。为什么朋友声明不起作用?

【问题讨论】:

  • 既然 ControllerMetals 在 Controller 中是私有的,为什么不在 ControllerMetas 中公开所有内容呢?显然嵌套的私有类与外部类是紧密耦合的。
  • 我有一个任务,我必须将我的内部类声明为外部类的私有成员。并且所有成员都必须是私有的。
  • Controller::start 在您加为好友时不存在。当您与它成为朋友时,您可以声明数据类型,但我认为您不能使用函数。转发声明ControllerMetals,以便您可以引用它,然后在函数之后正式定义它。为什么我不直接回答?

标签: c++ class nested friend


【解决方案1】:

问题

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

解决方案

我个人同意 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;


};

【讨论】:

    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2015-03-06
    • 2021-08-29
    • 1970-01-01
    • 2011-05-20
    相关资源
    最近更新 更多