C++ 如何实现向量<;类别>;模板&x27;s函数?

C++ 如何实现向量<;类别>;模板&x27;s函数?,c++,C++,我想实现这样一个模板 class animal{ } class beast : public animal { public: beast(string name){} void cry(){ cout<<"kuuuuu"<<endl; } } int main(){ vector<animal*> a; a.push_back(beast("tiger")) vector[0].cry(); } 类动物{ } 兽类:公共动物{ 公众: beast(字符串

我想实现这样一个模板

class animal{
}
class beast : public animal {
public:
beast(string name){}
void cry(){
cout<<"kuuuuu"<<endl;
}
}
int main(){
vector<animal*> a;
a.push_back(beast("tiger"))
vector[0].cry();
}
类动物{
}
兽类:公共动物{
公众:
beast(字符串名称){}
虚空呐喊(){

cout
animal
没有
cry
方法。因此您不能对animal调用
cry

此外,您还有许多语法错误,这会在这一行之前给您带来错误:

您的向量包含指针,您正试图将对象本身填充到其中


要访问对象指针指向的成员,您应该使用
->
,而不是

需要进行大量更改。
静态\u cast
对于调用
cry
方法至关重要

  • 类定义应以
    结尾;

  • 由于您创建了
    向量
    ,因此在推回之前需要
    新建
    对象

  • 当您调用函数
    cry
    时,您需要
    static\u将其转换回
    beast*
    ,并使用
    ->
    来调用cry函数

  • 类动物{
    };
    兽类:公共动物{
    公众:
    beast(std::string name){}
    虚空呐喊(){
    std::cout
    #包括
    #包括
    #包括
    使用名称空间std;
    类动物{
    公众:
    virtual void cry()=0;//声明公共虚拟cry方法
    };
    兽类:公共动物{
    公众:
    beast(字符串名称){
    }
    虚空呐喊(){
    cout代替.调用指向的beast对象的cry方法
    }
    
    请正确格式化您的代码,并修复所有与问题无关的编译器错误。很明显,您的
    类动物
    没有声明
    cry
    函数…可能重复使用
    std::vector
    ,而不是手动管理内存。这是一个很好的观点。但对于OP.I焦点来说,这可能有点太多了d关于更正和解释。
    class animal{
    
    };
    class beast : public animal {
    public:
     beast(std::string name){}
    void cry(){
    std::cout<<"kuuuuu"<<std::endl;
    }
    };
    int main(){
    std::vector<animal*> a;
    a.push_back(new beast("tiger"));
    (static_cast<beast*>(a[0]))->cry();
    }
    
    #include <vector>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class animal {
    public:
        virtual void cry() = 0; // declare public virtual cry method
    };
    
    class beast : public animal {
    public:
    
        beast(string name) {
        }
    
        void cry() {
            cout << "kuuuuu" << endl;
        }
    };
    
    int main() {
        vector<animal*> a;
        a.push_back(new beast("tiger")); // create new object and end with semicolon
        a[0]->cry(); // use -> instead of . to call cry method of beast object pointed at
    }