问题描述
- C++函数模板中使用输出流出现 operator<< 不明确错误
-
#include<iostream> #include<set> #include<string> using namespace std; template<class T> void print(T first, T last) { for (; first != last; ++first) { cout<<*first<<" "; /*在类IntSet中重载了<<,为什么还会出现operator<<不明确错误 ? ? ?*/ } cout << endl; } class IntSet { public: int x; bool exist; IntSet(int Integer) :x(Integer) { exist = true; } friend bool operator <(const IntSet &t1,const IntSet &t2); friend ostream & operator <<(ostream o, const IntSet &t); void setfalse() { exist = false; } }; IntSet & operator *(IntSet &t) { return t; } bool operator <(const IntSet &t1,const IntSet &t2) { return t1.x < t2.x; } ostream & operator <<(ostream &o, const IntSet &t) { if (t.exist) { o << t.x; return o; } else { return o; } } typedef multiset<IntSet> MY_SET; typedef multiset<IntSet>::iterator my_iter; int main() { MY_SET ms; int Integer; string cmd; int iter; cin >> iter; while (iter) { cin >> cmd; if (cmd == "add") { cin >> Integer; ms.insert(IntSet(Integer)); cout << ms.count(IntSet(Integer)) << endl; print(ms.begin(),ms.end()); } else if (cmd == "del") { cin >> Integer; cout << ms.count(IntSet(Integer)) << endl; my_iter p; pair<my_iter, my_iter> bounds = ms.equal_range(IntSet(Integer)); for (p = bounds.first; p != bounds.second; p++) const_cast<IntSet&>(*p).setfalse(); print(ms.begin(), ms.end()); } else if (cmd == "ask") { cin >> Integer; my_iter p; pair<my_iter, my_iter> bounds = ms.equal_range(IntSet(Integer)); int num=0; for (p = bounds.first; p != bounds.second; p++) { if (p->exist) num++; } if (ms.count(Integer)) { cout << 1 << " "<<num<<endl; } else { cout << 0 << " "<<0<<endl; } } iter--; } return 0; }
解决方案
IntSet & operator *(IntSet &t)
{
return t;
}
你这个重载的是乘法,不是取地址
时间: 2024-09-28 23:10:53