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

标签 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;

错误 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/

相关文章:

c++ - 无法运行 DLL 链接的 C++ exe。 "This program cannot be run in DOS mode."错误

c++ - libstdc++ 和 libc++ : operator>> on bitset 行为差异

c++以有效的方式重载加

python - 在 python 类上重写 __or__ 运算符

c++ - 如何在具有动态大小数组的模板类中重载 operator=

c++ - 错误 124 - SHFileOperation 的系统调用级别不正确

c++ - 从 `<<` 返回 `operator<<` 的结果

c++ - (n*2-1)%p : avoiding the use of 64 bits when n and p are 32 bits

C++ 运算符重载

c++ - C++ 中的运算符 <<, "no operator found which takes right hand-operator"和 "already has a body"错误