【发布时间】:2011-10-10 18:11:55
【问题描述】:
所以这就是交易,我想我需要就我正在使用的模式采取另一条路线,但我想我会先获得一些专家意见。
我有一个类 (UsingClass),它维护一个基类指针的动态列表。当向列表中添加一个新对象时,我必须弄清楚它是什么类型的对象,因为我不能真正让它以多态方式工作。下面的行标记为“这不会像我想要的那样工作!!”理想情况下,将多态地使用感兴趣的派生类中的 = 运算符,但不幸的是,它只使用 Base 类的默认 = 运算符......如果我将 Base 设为纯虚拟(基本上将其用于没有它自己的数据成员),但我真的不想让派生类拥有两者之间共有的成员(也许我只需要减少诱饵并这样做)。
我想我可能只是完全使用了错误的模式,但我不知道应该考虑哪些替代方案。
我知道代码不一定能编译,但请与我合作。提前致谢!
//code block
class Base {
protected:
int x;
float y;
string type; // default to Derived1 or Dervied2 depending on the object inst
public:
virtual int functionM(int l) = 0;
int functionN(int P);
};
class Derived1 : public Base {
protected:
int a;
public:
int functionM(int l);
float functionR(int h);
};
class Derived2 : public Base {
protected:
int b;
float r;
public:
int functionM(int l);
float functionR(int h);
};
#define MAX_ARRAYSIZE 10
class UsingClass {
private:
Base* myDerived1And2DynamicList[MAX_ARRAYSIZE];
int indexForDynamicList;
public:
void functionAddDerivedToList(*Base myInputPtr) {
if((indexForDyanmicList + 1) < MAX_ARRAYSIZE) {
if(myInputPtr->type == "Derived1") {
myDerived1And2DynamicList[indexForDyanmicList+1] = new Derived1;
*myDerived1And2DynamicList[indexForDyanmicList+1] = *myInputPtr; // THIS WILL NOT WORK LIKE I WANT IT TO!!
} else if (myInputPtr->type == "Derived2") {
myDerived1And2DynamicList[indexForDyanmicList+1] = new Derived2;
*myDerived1And2DynamicList[indexForDyanmicList+1] = *myInputPtr; // THIS WILL NOT WORK LIKE I WANT IT TO!!
}
}
} // end of void function
};
【问题讨论】:
-
您的问题不清楚。也许您应该首先告诉我们您真正想要实现的目标,而不是尝试修复您的解决方案......
-
在我看来你想要一个
clone()方法...谷歌克隆,你应该找到很多例子。 -
icu-project.org/docs/papers/cpp_report/… 这可以解决很多问题。
标签: c++ polymorphism clone copy-constructor assignment-operator