如何实现vector <class>模板的功能?

时间:2015-12-13 17:21:54

标签: 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();
}

我想实现类似的功能。但我的visualstudio找不到cry()函数。

拜托,我该怎么办?

3 个答案:

答案 0 :(得分:4)

animal没有cry方法。所以你不能在动物身上叫cry

此外,您还有许多语法错误,在此行之前应该会出错:

你的向量包含指针,你试图将对象本身填入其中。

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

答案 1 :(得分:1)

需要进行大量更改。static_cast对于调用cry方法至关重要。

  1. 类定义应以;

  2. 结尾
  3. 由于您创建了vector<animal*>,因此在推回之前需要new该对象。

  4. 当您调用函数cry时,您需要static_cast将其返回beast*并使用->代替.来调用此信息功能

  5. 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();
    }
    

答案 2 :(得分:1)

#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
}