2015-12-13 24 views
-5

我想要实现这样的一个模板,如何实现矢量<class>模板的功能?

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()函数。

请问我该怎么办?

+4

请正确格式化您的代码,并修复与问题无关的所有编译器错误。 –

+3

显然,你的'class animal'没有声明'cry'函数... –

+1

[为什么我们需要在C++中使用虚拟方法?](http://stackoverflow.com/questions/2391679/why-do -we-need-virtual-methods-in-c) – alain

回答

4

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

你也有许多语法错误,这应该给你的错误该行之前:

你的载体包含指针,你正在试图里面的东西对象本身。

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

1

需要做很多修改。 static_cast对于调用您的cry方法至关重要。因为你创造vector<animal*>

  1. 的类定义应与;

  2. 结束,你需要推前new对象返回。

  3. 当你调用该函数cry,你需要static_castbeast*和使用->代替.调用哭功能。

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(); 
} 
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 
} 
+0

使用'std :: vector >'而不是手动管理内存。 – GManNickG

+0

这是一个很好的观点。但是,对于OP来说,这可能会有点过分。我专注于纠正和解释。 – Elyasin