【发布时间】:2014-10-08 01:16:15
【问题描述】:
我有一个类,它结合了一些结构,例如这样:
struct _tRack1{
unsigned char shelf1;
unsigned int shelf2;
float shelf3;
};
struct _tRack2{
char shelf1;
int shelf2;
char shelf3;
char shelf4;
};
struct _tRack3{
char shelf1;
unsigned int drawer[5];
};
class Catalog
{
public:
_tRack1 *localdata1;
_tRack2 *localdata2;
_tRack3 *localdata3;
int index;
Catalog(int recktype){
localdata1 = NULL;
localdata2 = NULL;
localdata3 = NULL;
index = recktype;
switch(recktype){
case 1: *localdata1 = new _tRack1; break;
case 2: *localdata2 = new _tRack2; break;
case 3: *localdata3 = new _tRack3; break;
}
};
~Catalog(){
if(localdata1 != NULL) delete localdata1;
if(localdata2 != NULL) delete localdata2;
if(localdata3 != NULL) delete localdata3;
};
int someMethod(_tRack1){/*...*/};
int someMethod(_tRack2){/*...*/};
int someMethod(_tRack3){/*...*/};
};
int main()
{
Catalog *foo = new Catalog(1);
Catalog *bar = new Catalog(3);
/*...*/
if(foo->index>1) foo->localdata1->shelf1=-3;
else foo->localdata1->shelf1=3;
if(bar->index>1) bar->localdata1->shelf1=-3;
else bar->localdata1->shelf1=3;
if(bar->index==3) bar->localdata3->drawer[0] = 0xDEADBEAF;
/*...*/
delete foo;
delete bar;
return 0;
}
我知道公开结构并不好,但在现实生活中结构非常复杂,因此不可能创建访问不同结构字段的方法。 我想找到一种隐藏结构类型的方法。要访问这样的数据:
if(foo->index>1) foo->data->shelf1=-3;
else foo->data->shelf1=3;
if(bar->index>1) bar->data->shelf1=-3;
else bar->data->shelf1=3;
if(bar->index==3) bar->data->drawer[0] = 0xDEADBEAF;
有可能吗?
【问题讨论】:
-
为什么是多态...?
-
您希望 Catalog 根据条件仅包含三个结构中的一个?我无法从代码中判断结构是否在逻辑上相互关联以建议基类。也许你可以只使用一个联合。
-
嗯,工会?听起来不错,我试试……
-
这不是问题,但
if(foo->index>1) foo->localdata1->shelf1=-3;会在 index==2 时触发分段错误! -
嗯,是时候读一本关于面向对象编程的书了。它不仅会提到多态性,还会提到封装。 :)
标签: c++ class oop polymorphism