The*_* do 1 c++ operator-overloading
#include "stdafx.h"
#include "Record.h"
template<class T>//If I make instead of template regular fnc this compiles
//otherwise I'm getting an error (listed on the very bottom) saying
// that operator << is ambiguous, WHY?
ostream& operator<<(ostream& out, const T& obj)
{
out << "Price: "
<< (obj.getPrice()) << '\t'//this line causes this error
<< "Count: "
<< obj.getCount()
<< '\n';
return out;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<Record> v;
v.reserve(10);
for (int i = 0; i < 10; ++i)
{
v.push_back(Record(rand()%(10 - 0)));
}
copy(v.begin(),v.end(),ostream_iterator<Record>(cout, "\n"));
return 0;
}
//Record class
class Record
{
private:
int myPrice_;
int myCount_;
static int TOTAL_;
public:
Record(){}
Record(int price):myPrice_(price),myCount_(++TOTAL_)
{/*Empty*/}
int getPrice()const
{
return myPrice_;
}
int getCount()const
{
return myCount_;
}
bool operator<(const Record& right)
{
return (myPrice_ < right.myPrice_) && (myCount_ < right.myCount_);
}
};
int Record::TOTAL_ = 0;
Run Code Online (Sandbox Code Playgroud)
错误2错误C2593:'operator <<'不明确
背后的概念operator<<( ostream &, ... )是每个类都有自己的重载,以一种有意义的方式处理特定的类.
这意味着你可以operator<<( ostream &, const Record & )处理Record对象,operator<<( ostream &, const std::string & )处理标准字符串,以及operator<<( ostream &, const FooClass & )处理FooClass对象.这些函数中的每一个都知道如何处理它声明的对象类型,因为它们中的每一个都需要不同的处理.(例如getPrice()/ getCount()for Record,或getFoo()/ getBar()for FooClass.)
你的模板正在践踏整个概念.通过将其定义为模板函数(可以匹配任何类),您不仅要碰到operator<<()标准/代码库中已有的许多定义,而且还要碰撞所有可能的重载.
编译器如何决定是使用operator<<( ostream &, const std::string & )还是模板?它不能,所以它绝望地抛出手并放弃.这就是错误告诉你的.
| 归档时间: |
|
| 查看次数: |
1939 次 |
| 最近记录: |