当班级想要结合

bob*_*obo 6 c++ coupling class

我遇到了两个曾经很好分开的课程的问题,但现在他们想要结合.

没有太多了解问题的细节,这里是:

我曾经有一个包含3个空位顶点的三角类.

class Triangle
{
    Vertex a,b,c ; // vertices a, b and c
} ;
Run Code Online (Sandbox Code Playgroud)

程序中有许多Triangle实例,因此每个实例都保留了自己的顶点副本.构件的功能,例如getArea(),getCentroid()等写在类Triangle,和由于每个Triangle实例具有顶点A,B和C的副本,寻找区域或质心对其他类没有依赖性.应该是!

然后,由于其他原因,我想转移到顶点数组/索引缓冲区样式表示.这意味着所有顶点都存储在一个位于Scene对象中的单个数组中,并且每个Triangle顶点仅保留顶点的REFERENCES Scene,而不保留顶点本身的副本.起初,我尝试切换指针:

class Scene
{
    std::vector<Vertex> masterVertexList ;
} ;

class Triangle
{
    Vertex *a,*b,*c ; // vertices a, b and c are pointers
    // into the Scene object's master vertex list
} ;
Run Code Online (Sandbox Code Playgroud)

(如果您对这些好处感到疑惑,我之所以这样做是因为大多数情况下共享顶点的三角形.如果*a移动,那么使用该顶点的所有三角形都会自动更新).

这本来是一个非常好的解决方案!但它没有可靠的工作,因为std :: vector使指针无效,我在类中使用std :: vector作为主顶点列表Scene.

所以我不得不使用整数:

class Triangle
{
    int a,b,c ; // integer index values
    // into the Scene object's master vertex list
} ;
Run Code Online (Sandbox Code Playgroud)

但是现在我遇到了这个新的耦合问题:要找到自己的区域或质心,类Triangle需要访问class Scene之前没有的区域.好像我已经把事情搞砸了,但事实并非如此.

WWYD?

Col*_*ine 3

在我看来,你的三角形确实取决于你的场景(因为它的顶点都是该特定场景的成员),所以让对象这样做并不可耻。事实上,我可能会给三角形一个强制性的场景*成员。