比方說,你有這樣的:從抽象基類指針複製數據的C + +?
class foo {
public:
virtual int myFunc() = 0;
///...
virtual bool who() = 0; // don't want to implement this
};
class bar : public foo {
public:
int myFunc() {return 3;}
//...
bool who() {return true;} // don't want to implement this
};
class clam : public foo {
public:
int myFunc() {return 4;}
//...
bool who() {return false;} // don't want to implement this
};
int main() {
std::vector<foo*> vec (2, NULL);
vec[0] = new bar();
vec[1] = new clam();
// copy vec and allocate new ptrs as copies of the data pointed to by vec[i]
std::vector<foo*> vec2 (vec.size(), NULL);
for (int i=0; i<vec.size(); ++i) {
// obviously not valid expression, but it would be nice if it were this easy
//vec2[i] = new foo(*vec[i]);
// the hard way of copying... is there easier way?
if (vec[i]->who()) {
vec2[i] = new bar (* static_cast<bar* >(vec[i])) ;
} else {
vec2[i] = new clam(* static_cast<clam*>(vec[i]));
}
}
return 0;
}
我要的是有編譯器查找在簿記和分配/複印VEC 2的一些簡單的方法[I]根據存儲類型的* VEC [I] 。解決方法是創建一個虛函數,該函數基本上返回一個指定* vec [i]類型的值,然後根據該值進行有條件分配。
大多數時候,當你發現自己寫'如果(對象是某種類型){做一些事情; } else if(object是其他類型){做別的事; }'你應該添加一個新的虛函數來封裝不同的行爲,就像Igor的答案一樣;這就是他們的目標。 – Oktalist