This topic has been archived. It cannot be replied.
-
工作学习 / IT技术讨论 / 请教C++大师一个问题,多谢,请进:我有一基类shape,继承类circle, square。在一个function
void f(string s)里,如果s == "circle"就shape* ss = new circle;如果s == "square" 就shape* ss = new sqaure。有没有什么办法不需要像下面那样一一列出
if(s == "circle")
ss = new circle;
else if(s == "square")
ss = new square;
我当然不能写 ss = new s;
我知道在Java中可用Class.forName(s).newInstance。C++中有类似的做法吗?
-fisher38(渔父);
2002-8-7
{389}
(#679989@0)
-
up
-fisher38(渔父);
2002-8-7
(#680062@0)
-
This is a kind of abstract factory pattern. The answer for your question is "no"
-handler(憨豆乐);
2002-8-7
(#680086@0)
-
No. This is not abstract factory. It is named factory pattern.
-contact(Contact);
2002-8-8
(#680869@0)
-
没有, 不过你可以用map自己写一个table。
-taop(心随碧草又迎风);
2002-8-7
(#680090@0)
-
You can....void f(string s)
{
Shape * sp;
if (strcmp("circle",s) == 0)
{
sp = (Circle *) new Circle;
}
.............................
}
-mage(馅饼);
2002-8-8
{158}
(#680890@0)
-
C++没有提供类似的类.但可以根据需要写一个. 把这部分CODE写成一个FACTORY class便于维护.
-pixel(pixel);
2002-8-8
(#680892@0)
-
对,看一下COM的原理就会做了。
-flying_snow(飞雪浮冰);
2002-8-8
(#681118@0)