C++模板问题
对于以下代码:
#include <map>
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Foo{
public:
map<int, T> reg;
map<int, T>::iterator itr;
void add(T str, int num) {
reg[num] = str;
}
void print() {
for(itr = reg.begin(); itr != reg.end(); itr++) {
cout << itr->first << " has a relationship with: ";
cout << itr->second << endl;
}
}
};
int main() {
Foo foo;
Foo foo2;
foo.add("bob", 10);
foo2.add(13,10);
foo.print();
return 0;
}
我收到错误:
type std::map<int, T, std::less<int>, std::allocator<std::pair<const int, T> > > is not derived from type Foo<T>
我从未使用过 C++ 模板 - 这是什么意思?
For the following code:
#include <map>
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Foo{
public:
map<int, T> reg;
map<int, T>::iterator itr;
void add(T str, int num) {
reg[num] = str;
}
void print() {
for(itr = reg.begin(); itr != reg.end(); itr++) {
cout << itr->first << " has a relationship with: ";
cout << itr->second << endl;
}
}
};
int main() {
Foo foo;
Foo foo2;
foo.add("bob", 10);
foo2.add(13,10);
foo.print();
return 0;
}
I get the error:
type std::map<int, T, std::less<int>, std::allocator<std::pair<const int, T> > > is not derived from type Foo<T>
I've never used C++ templates - What does this mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您声明 Foo 的实例时,您缺少类型。
在您的情况下,您需要:
您还需要将关键字 typename 添加到行中:
请参阅 此处了解为什么您需要 typename。
编辑,这是在本地编译和运行的代码的修改版本:
You're missing the type when you declare instances of Foo.
In your case, you would want:
You will also need to add the keyword typename to the line:
See here for why you'll need typename.
Edit, here's a modified version of your code that compiles and runs locally: