简体   繁体   English

在C ++中交织两个类是一种不好的做法吗?

[英]Is it a bad practice to intertwine two classes in c++?

I give the following examples to illustrate my question: 我提供以下示例来说明我的问题:

class B;
class A
{
 public:


   class B *pB;

};

class B
{
  public:

     void perform(A &obj)
     {

     }
};

In the above two classes. 在以上两节课中。 class A has a pointer to class B. class B has a function that will work on class A object. 类A具有指向类B的指针。类B具有将对类A对象起作用的函数。 Though it can compile, I was wondering whether this is not a good practice for designing two classes as they are intertwined. 尽管它可以编译,但我想知道这是否不是设计两个相互交织的类的好习惯。 If this is bad design, do you have some ideas to avoid it? 如果这是不好的设计,您有一些想法可以避免吗? Thanks. 谢谢。

Having two concrete classes rely directly on one another can get you into trouble. 有两个具体的类直接相互依赖会给您带来麻烦。

It is often better to "program to an interface" . 通常最好对接口进行编程 There is a long discussion here under the title "Program to an interface, not an implementation", which draws out why decoupling matters 还有很长的讨论这里的标题下的“计划,以一个接口,而不是实现”,吸引了为什么去耦事项

In your example, void perform(A &obj) could instead take an abstract base class that A derives from. 在您的示例中, void perform(A &obj)可以采用A派生的抽象基类。 It might be worth having an interface that A uses in it's member variable too, but there' no suggested usage in your example to go on. 也许也值得在其成员变量中使用A接口,但是在您的示例中没有建议的用法。

Why is this "better"? 为什么这个“更好”? For starters, it will make you think about encapulsation - and what specifically the interface should be exposing. 对于初学者,它会让您考虑强制性-接口应该具体暴露什么。

It will also allow you to use different conrete instantions of the class, say for testing purposes. 它还将允许您使用类的不同具体实例,例如出于测试目的。

If you use an interface, you can change the conrete classes separately... there are many advantages. 如果使用接口,则可以分别更改具体类...有很多优点。

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

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