找了一个c++,classtemplate的例子,为啥不能编译通过?

kofwr 2006-12-22 09:28:18
// class templates
#include <iostream>
using namespace std;

template <class T>
class pair {
T a, b;
public:
pair (T first, T second)
{a=first; b=second;}
T getmax ();
};

template <class T>
T pair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}

int main () {
pair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}


错误输出:
g++ ClassTemplate.cpp -o ClassTemplate.exe
ClassTemplate.cpp:15: syntax error before `::' token
ClassTemplate.cpp:16: ISO C++ forbids declaration of `getmax' with no type
ClassTemplate.cpp: In function `int getmax()':
ClassTemplate.cpp:17: `T' undeclared (first use this function)
ClassTemplate.cpp:17: (Each undeclared identifier is reported only once for
each function it appears in.)
ClassTemplate.cpp:17: parse error before `;' token
ClassTemplate.cpp:18: `retval' undeclared (first use this function)
ClassTemplate.cpp:18: `a' undeclared (first use this function)
ClassTemplate.cpp:18: `b' undeclared (first use this function)
ClassTemplate.cpp: In function `int main()':
ClassTemplate.cpp:23: use of `pair' is ambiguous
ClassTemplate.cpp:6: first declared as `template<class T> class pair' here
C:/MinGW/include/c++/3.2.3/bits/stl_pair.h:69: also declared as `
template<class _T1, class _T2> struct std::pair' here
ClassTemplate.cpp:23: parse error before `>' token
ClassTemplate.cpp:24: `myobject' undeclared (first use this function)
...全文
102 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
晨星 2006-12-22
  • 打赏
  • 举报
回复
都四星了,还为这80分郁闷。。。
jixingzhong 2006-12-22
  • 打赏
  • 举报
回复
。。。。。。。。。。。。。

就看了一会就慢了,
郁闷啊
jixingzhong 2006-12-22
  • 打赏
  • 举报
回复
template <class T>
class pair1 {
T a, b;
public:
pair1 (T first, T second)
{a=first; b=second;}
T getmax ();
};

template <class T>
T pair1<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
晨星 2006-12-22
  • 打赏
  • 举报
回复
应该是跟标准库里的名字起冲突了。
在我的编译器上(g++ 3.4.4),把所有的“pair”改在另外一个名字就没问题了。
sopro 2006-12-22
  • 打赏
  • 举报
回复
在VS2003上面可以编过,输出100

64,685

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧