我有一个指向从同一基类派生的对象的指针向量。问题是在调用函数(而不是方法)时忘记了原始对象的类型。
class Cat{
//base class
public:
virtual void growl() = 0;
};
class HouseCat : public Cat{
//derived class
public:
void growl(){};
};
class AlleyCat : public Cat{
//derived class
public:
void growl(){};
};
void function(HouseCat& a){};
void function(AlleyCat& a){};
int main(){
vector<Cat*> cats;
cats.push_back(new HouseCat);
cats.push_back(new AlleyCat);
function(*(cats[0])); //error: cannot convert parameter 1 from 'Cat' to 'HouseCat &'
(cats[0])->growl(); //this works though
}
有解决方法吗?