歧义运算符<< [英] Ambiguous operator <<

查看:103
本文介绍了歧义运算符<<的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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错误C2593:操作员<<"模棱两可

推荐答案

首先,您需要更仔细地阅读错误消息.作为替代方案,请考虑将语句分解,如下所示:

First, you need to read the error message more carefully. As an alternative, consider breaking the statement up, something like this:

out << "Price: ";
out << (obj.getPrice());
out << "\tCount: ";
out << obj.getCount();
out << '\n';

当您这样做时,您将意识到真正导致问题的原因不是 ,而是尝试打印getPrice()的位置,而是尝试打印"Price: "的位置.

When you do, you'll realize that what's really causing the problem is not where you try to print out getPrice(), but where you try to print out "Price: ".

之所以出现此问题,是因为编译器不知道是使用普通的重载来打印字符串,还是使用所定义的模板来打印字符串.后者将导致无限递归,并且由于它要求您可以/可以在其上调用getPricegetCount的对象来正确编译,因此它实际上无法编译-但它具有匹配的签名,因此编译器说这是模棱两可的,到此为止.

The problem is arising because the compiler doesn't know whether to use the normal overload to print out the string, or to use the template being defined to print it out. The latter would cause infinite recursion, and it couldn't actually compile since it requires an object on which you can/could call getPrice and getCount to compile correctly -- but it has a signature that matches, so the compiler says it's ambiguous, and that's the end of that.

这篇关于歧义运算符&lt;&lt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆