简体   繁体   English

C ++从另一个类访问私有结构

[英]C++ Accessing a private structure from another class

I have a class as shown below: 我有一个如下所示的课程:

class B;
class A
{
   public:
       A();
      ~A();
      void createStuff(.......); //??

  private:
      B *b;
};

The object B contains another of class 'C' which has about 20 class member variables. 对象B包含另一个类'C',它有大约20个类成员变量。

I want the user of class A to be able to call the function createStuff(...) with a set of arguments so that I can construct the object C. What is the best way of doing this? 我希望类A的用户能够使用一组参数调用函数createStuff(...),以便我可以构造对象C.这样做的最佳方法是什么?

类授予访问其私有成员的机制称为友谊。

With what you have posted it looks like something like this may work: 根据您发布的内容,看起来像这样的东西可能会起作用:

class B
class A:
{
   public:
       A();
      ~A();
      void ceateStuff(.......); //??

  private:
      B *b
}
void A::createStuff(argument1, argument2...)
{
    C = new C(argument1, argument2...) //You now have an instance of C with the arguments pass in to createStuff();

} }

The variable of type C belongs to class B; 类型C的变量属于B类; it mediates the access to the data in C. Class B has constructors; 它调解了对C中数据的访问.B类有构造函数; you will use those to set the variable of class B in order, and it is B's job to ensure that the C is correctly managed. 您将使用它们按顺序设置B类变量,确保正确管理C是B的工作。

If you need more control over C, then you have a design problem. 如果您需要更多地控制C,那么您就会遇到设计问题。 Either your class A needs its own variable of class C to control, or class B does not provide the tools you need and needs fixing, or you are misguided in thinking you need access to, and therefore direct control over, the contents of the variable of class C. 你的A类需要它自己的C类变量来控制,或者B类不提供你需要和需要修复的工具,或者你误以为你需要访问变量的内容,从而直接控制变量的内容C班

The Law of Demeter is a guide in such scenarios; 得墨忒耳定律是这种情景的指南; you seem to be wanting to contravene it. 你似乎想要违背它。

In any case you should look at B class, how it implement initialization of C object, can it be controlled (If can't - you should extend interface of class B and add this functionality)? 无论如何你应该看看B类,它如何实现C对象的初始化,是否可以控制(如果不能 - 你应该扩展B类的接口并添加这个功能)?

If C definition is accesible for A maybe you can use constructor of B in such way: 如果A可以访问C定义,也许你可以这样使用B的构造函数:

void A::createStuff( const C& c)
{
    b = new B(c); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM