C++ C++;模板问题
对于以下代码:C++ C++;模板问题,c++,templates,C++,Templates,对于以下代码: #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) {
#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;
}
#包括
#包括
#包括
使用名称空间std;
模板
福班{
公众:
地图注册;
迭代器itr;
无效添加(T str,int num){
reg[num]=str;
}
作废打印(){
对于(itr=reg.begin();itr!=reg.end();itr++){
cout first您在声明Foo实例时缺少类型
在您的情况下,您需要:
Foo<std::string> foo;
Foo<int> foo2;
Foo-Foo;
富富2;
您还需要将关键字typename添加到行中:
typename map<int, T>::iterator itr;
typename映射::迭代器itr;
查看为什么需要typename
编辑,这里是编译并在本地运行的代码的修改版本:
#include <map>
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Foo{
public:
map<int, T> reg;
typename 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<std::string> foo;
Foo<int> foo2;
foo.add("bob", 10);
foo2.add(13,10);
foo.print();
return 0;
}
#包括
#包括
#包括
使用名称空间std;
模板
福班{
公众:
地图注册;
typename映射::迭代器itr;
无效添加(T str,int num){
reg[num]=str;
}
作废打印(){
对于(itr=reg.begin();itr!=reg.end();itr++){
首先谢谢,但这似乎并没有修复错误-但它确实修复了一些其他错误。我刚刚添加到注释中的版本在本地编译并运行。+1感谢您包含错误消息。下次还请指出它在哪一行(在源代码中添加注释是实现此目的的一个好方法)。
#include <map>
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Foo{
public:
map<int, T> reg;
typename 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<std::string> foo;
Foo<int> foo2;
foo.add("bob", 10);
foo2.add(13,10);
foo.print();
return 0;
}