以下代码无法编译:
#include <iostream>
#include <set>
#include <utility>
using namespace std;
template <typename T1, typename T2>
class meta {
pair<T1,T2> xy_pair;
public:
/* meta(const T1 & t1, const T2 & t2) :
xy_pair.first(t1),
xy_pair.second(t2)
{}*/
meta() :
xy_pair.first(T1()),
xy_pair.second(T2())
{}
void print() const{
cout << xy_pair.first << endl;
cout << xy_pair.second << endl;
}
};
int main(){
meta<int,int> met_xy;
}
我收到以下编译错误:
[root@localhost STL]# g++ -std=c++0x sets.cpp -o sets
sets.cpp: In constructor ‘meta<T1, T2>::meta()’:
sets.cpp:16:16: error: expected ‘(’ before ‘.’ token
sets.cpp:16:16: error: expected ‘{’ before ‘.’ token
sets.cpp: In member function ‘void meta<T1, T2>::print() const’:
sets.cpp:20:29: error: expected primary-expression before ‘,’ token
sets.cpp:20:32: error: expected primary-expression before ‘>’ token
sets.cpp:20:33: error: expected primary-expression before ‘.’ token
sets.cpp:21:29: error: expected primary-expression before ‘,’ token
sets.cpp:21:32: error: expected primary-expression before ‘>’ token
sets.cpp:21:33: error: expected primary-expression before ‘.’ token
答案 0 :(得分:3)
您不能像这样在初始化列表中初始化成员对象的各个子成员。做到这一点
meta() : xy_pair(T1(), T2()) {}
或只是
meta() {}
或者实际上完全省略了默认构造函数 - 编译器生成的构造函数会做同样的事情。
答案 1 :(得分:2)
您的代码应该如下所示:
#include <utility>
#include <ostream>
#include <iostream>
template <typename T1, typename T2>
class meta {
std::pair<T1, T2> xy_pair;
public:
meta(const T1 & t1, const T2 & t2) : xy_pair(t1, t2) { }
// note initialization of the whole member xy_pair, not its members
meta() : xy_pair() { }
void print() const {
cout << xy_pair.first << endl;
cout << xy_pair.second << endl;
}
};
int main() {
meta<int, int> meta_xy;
}