gpt4 book ai didi

c++ - 不明确的运算符 <<

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:24 25 4
gpt4 key购买 nike

#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;

错误 2 error C2593: 'operator <<' is ambiguous

最佳答案

背后的概念operator<<( ostream &, ... )是每个类都可以有自己的重载,以一种有意义的方式处理特定的类。

这意味着你得到 operator<<( ostream &, const Record & )它处理 Record 对象,以及 operator<<( ostream &, const std::string & )处理标准字符串,operator<<( ostream &, const FooClass & )它处理 FooClass 对象。这些函数中的每一个都知道如何处理为其声明的对象类型,因为它们中的每一个都需要不同的处理。 (例如 getPrice()/getCount() 代表 Record ,或 getFoo()/getBar() 代表 FooClass 。)

您的模板践踏了整个概念。通过将其定义为模板函数(匹配任何 类),您不仅会与 operator<<() 的许多定义发生冲突。已经在标准/您的代码库中,但是所有可能的重载。

编译器如何决定是否使用 operator<<( ostream &, const std::string & )还是你的模板?它做不到,所以它绝望地举起双手放弃了。这就是错误告诉您的内容。

关于c++ - 不明确的运算符 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3319837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com