所以這裏是交易,我認爲我需要去關於我使用的模式的另一條路線,但我想我會首先得到一些專家意見。多態性與=操作符使用指針基類
我有一個類(UsingClass),它維護基類指針的動態列表。當向列表中添加一個新對象時,我必須弄清楚它是什麼類型的對象,因爲我無法真正以多態的方式使它工作。下面一行標記爲「這不會像我想要的那樣工作!」理想情況下多態地使用來自Derived類的=運算符,但不幸的是它只使用Base類的default =運算符......如果我將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()'方法... google clone,你應該找到大量的例子。 –
http://icu-project.org/docs/papers/cpp_report/the_assignment_operator_revisited.html這可以清理很多事情。 – DumbCoder