为了账号安全,请及时绑定邮箱和手机立即绑定

请问:下面程序为什么在连接时有错,而在不用类模板时又没有错啊?

请问:下面程序为什么在连接时有错,而在不用类模板时又没有错啊?

C++
郎朗坤 2023-04-09 13:09:59
另外:operator() 、operator== 在程序中是究竟是怎样被调用的#include <iostream> #include <set> using namespace std; template <class T> class RuntimeCmp { public: enum cmp_mode {normal, reverse}; private: cmp_mode mode; public: //constructor for sorting criterion //-default criterion uses value normal RuntimeCmp (cmp_mode m=normal) : mode(m) { } //comparision of elements bool operator() (const T& t1, const T& t2) const { return mode == normal ? t1 < t2 : t2 < t1; } //comparision of sorting criteria bool operator== (const RuntimeCmp& rc) { return mode == rc.mode; } }; //type of a set that uses this sorting criterion typedef set<int,RuntimeCmp<int> > IntSet; void fill (IntSet& Set) { //fill insert elements in random order Set.insert(4);  Set.insert(7); Set.insert(5); Set.insert(1); Set.insert(6); Set.insert(2); Set.insert(5); } template <class T> int main() { //create, fill, and print set with normal element order //-uses default sorting criterion IntSet coll1; fill(coll1); copy(coll1.begin(),coll1.end(),ostream_iterator<int>(cout," "));cout<<endl;RuntimeCmp<int> reverse_order(RuntimeCmp<int>::reverse); //create, fill, and print set with reverse element order IntSet coll2(reverse_order);  fill(coll2); copy(coll2.begin(),coll2.end(),ostream_iterator<int>(cout," "));cout<<endl;//assign elements AND sorting criterion coll1 = coll2; coll1.insert(3); // PRINT_ELEMENTS coll1copy(coll1.begin(),coll1.end(),ostream_iterator<int>(cout," "));cout<<endl;//just to make sure... if (coll1.value_comp() == coll2.value_comp()) { cout << "coll1 and coll2 have same sorting criterion" << endl; } else { cout << "coll1 and coll2 have different sorting criterion" << endl; } return 0;}
查看完整描述

2 回答

?
达令说

TA贡献1821条经验 获得超6个赞

根据你的出错信息来看,要么你没有main,要么你有多余的main
这些运算符的调用和函数是一样的 
他们有参数,也有返回类型,当然并不是所有的都是这样,如 operator type()就没有返回类型,其实type就是,调用我也不太清楚.如class operator+(),如是全局的则()内的一个是左操作数,一个是右操作数 ,class代表返回值,operator==类似

查看完整回答
反对 回复 2023-04-12
?
喵喔喔

TA贡献1735条经验 获得超5个赞

没写main函数呗

查看完整回答
反对 回复 2023-04-12
  • 2 回答
  • 0 关注
  • 86 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信