【发布时间】:2020-11-04 22:13:26
【问题描述】:
我真的对 OOP 背后的想法感到惊讶,因为我发现考虑类和对象要容易得多,就好像它们是真实的一样。我有一个基类 Tooth 和不同牙齿组的派生类(它们有自己的细节)。它们的构造函数将绘制的纹理作为参数; 对于上牙,它是这样的:
class Tooth
{
public:
Tooth(Texture &texture);
};
class Molar : public Tooth { };
class Premolar : public Tooth { };
class Frontal : public Tooth { };
main()
{
Molar *molar[6];
Premolar *premolar[4];
Frontal *frontal[6];
Texture uppertextures[8]; //only 8 textures, since the other half of the teeth are mirrored
Tooth* upperTeeth[16] = { molar[0], molar[1], molar[2], premolar[0], premolar[1], frontal[0], frontal[1], frontal[2], frontal[3], frontal[4], frontal[5], premolar[2], premolar[3], molar[3], molar[4], molar[5] }; // < the order in which the teeth have to be added to the graphic scene;
int x = 0 //for the position of the tooth on the screen;
int texture = 0; //we will need it to assign the textures in order;
for(int i = 0; i<16; i++)
{
upperTeeth[16] = new !?!?!?(uppertextures[i])
upperTeeth[16]->setPositionX(i+x) // some function for setting the position on the screen from left to right;
if(i<8) texture++; //setting the textures for the teeth on the left;
if(i>8) texture--; //setting the textures for the teeth on the right(the same, but in reverse order);
upperTeeth[16]->setPositionY(y)
}
}
如您所见,问题在于分配。我想以与创建基类数组相同的方式创建 new[],并填写派生类的顺序,其中对象出现。当然,如果你有完全不同的解决方案,你可以分享它,但这是我能想到的最聪明的方法。
【问题讨论】:
-
您可以首先观察将任何内容分配给
upperTeeth[16]是未定义的行为。所以,你已经处于崩溃领域,就在起跑门外。就学习如何正确构造对象而言,这应该很好地涵盖in every good C++ textbook。你的教科书中有没有关于这个主题的具体内容,你不清楚,并且有疑问?你不会通过在这里提问来学习 C++,而只能通过一本好的教科书来学习。 -
很难理解你真正想要达到的目标。
upperTeeth[16] = new !?!?!?(uppertextures[i])应该如何知道要实例化哪种对象?辨别因素是什么?请注意,您可能会对工厂模式感兴趣 -
不,你应该做的是get a good C++ textbook, and work your way through it。 C++ 是当今使用的最复杂和最难的通用编程语言,在 stackoverflow.com 上的简短回答中根本不可能完全解释所有内容。 SO 确实不是教科书的替代品,而只是一个特定的 Q/A 网站。
-
这有点类似于尝试学习如何开车而不左转。技术上可行,但并非真正可取。
-
编程必须实用,这意味着不要添加不会增加价值的东西。我认为为不同种类的牙齿设置不同的类没有任何价值。如果患者有一些无法分类的异常牙齿怎么办?
标签: c++ for-loop derived-class