嵌套类与基础类中的派生类结交之间的区别 [英] Difference between nested class and befriending a derived class in base class

查看:84
本文介绍了嵌套类与基础类中的派生类结交之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建以所有成员为私有成员的类P和从P派生的友善类B之间有什么区别

What is the difference between creating class P with all members as private and befriending class B which is derived from P

class P
{
private:
        int i;
        friend class B;
};

class B: public P
{
public:
        void get()
        {
                cout <<i;
        }
};

int main()
{

        B obj2;
        obj2.get();
        return 0;
}

vs

在一个类中创建一个类,以便没有人可以使用隐藏的类(子类),这样就很容易进行维护,而不必担心会破坏其他人的依赖代码.

Creating a class within a class so that nobody can use the hidden class(subclass) it would be easy for maintanence without having to worry about breaking someone elses dependent code.

在哪种情况下,我们要从以上(或任何其他(如果有的话))中选择哪种设计?

In which situation do we choose which design from the above(or any other if any)?

此问题是推荐答案

不要做您建议的事情:它的设计不好,并且有循环依赖的可能.请改用受保护的成员.

Don't do what you suggest: its bad design and there's a chance of circular dependencies. Use protected members instead.

class P
{
protected:
    int i = 42;
};

#include <iostream>

class B : public P
{
public:
    void get()
    {
        std::cout << i << std::endl;
    }
};

int main()
{
    B Bobj;
    Bobj.get();

    std::cin.ignore();
    return 0;
}

这篇关于嵌套类与基础类中的派生类结交之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆