假设你有这个:
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 [i]类型分配/复制vec2 [i]的简单方法。解决方法是创建一个虚函数,它基本上返回一个值,指定* vec [i]的类型,然后根据它进行条件分配。
答案 0 :(得分:4)
一种常见的方法是这样的:
class foo {
public:
virtual foo* clone() = 0;
};
class bar : public foo {
public:
virtual bar* clone() { return new bar(*this); }
};
class clam : public foo {
public:
virtual clam* clone() { return new clam(*this); }
};
答案 1 :(得分:0)
一种方法是使用动态强制转换来确定对象的类型,例如在此完成(Finding the type of an object in C++)。但最简单的方法可能是使用typeid。
(假设您想要保持使用类型作为限定词的方式,否则我会推荐Joachim或Igor作为更好的选择:))
答案 2 :(得分:0)
您可以使用dynamic_cast进行向下转换并测试类型
bar* pbar = dynamic_cast<bar*>(vec[i])
if (pbar) {
vec2[i] = new bar ( * static_cast<bar* >(vec[i]) ) ;
} else {
vec2[i] = new clam( * static_cast<clam*>(vec[i]) );
}
请参阅dynamic_cast中的更多信息 http://www.cplusplus.com/doc/tutorial/typecasting/