2012-07-19 145 views
2

我收到此操作员重载错误。下面是我得到的错误:重载<<操作员错误

Angle.cpp:466: error: ambiguous overload for 'operator<<' in '(+out)->std::basic_ostream<_Elem, _Traits>::operator<< [with _Elem = char, _Traits = std::char_traits](((const Angle*)this)->Angle:: getDegrees()) << "\37777777660"'

这里是我的类重载<<操作

#ifndef OUTPUTOPS_H 
#define OUTPUTOPS_H 1 

#include <ostream> 
#include "BoolOut.h" 

// Prints the output of an object using cout. The object 
// must define the function output() 
template< class T > 
std::ostream& operator<<(std::ostream& out, const T& x) 
{ 
    x.output(out); 

    return out; 
} 

#endif // OUTPUTOPS_H 

问题发生在这里:

void Angle::output(std::ostream& out) const 
{ 
    out << getDegrees() << "°"; 
} 

哪些奇怪的是没有发生从getDegrees(),但从字符串。我尝试将字符串更改为“你好”,以确保它不是符号,但我收到了同样的错误。

下面是代码的排除无关的代码的其余部分:

// Angle.h 

#include "OutputOps.h" 
// End user added include file section 

#include <vxWorks.h> 
#include <ostream> 

class Angle { 

public: 
    // Default constructor/destructor 
    ~Angle(); 

    // User-defined methods 
    // 
    // Default Constructor sets Angle to 0. 
    Angle(); 
    // 
    ... 
    // Returns the value of this Angle in degrees. 
    double getDegrees() const; 
    ... 
    // Prints the angle to the output stream as "x°" in degrees 
    void output(std::ostream& out) const; 

}; 

#endif // ANGLE_H 


// File Angle.cpp 

#include "MathUtility.h" 
#include <math.h> 
// End user added include file section 

#ifndef Angle_H 
#include "Angle.h" 
#endif 


Angle::~Angle() 
{ 
    // Start destructor user section 
    // End destructor user section 
} 

// 
// Default Constructor sets Angle to 0. 
Angle::Angle() : 
radians(0) 
{ 
} 

... 
// 
// Returns the value of this Angle in degrees. 
double Angle::getDegrees() const 
{ 
    return radians * DEGREES_PER_RADIAN; 
} 

// 
// Returns the value of this Angle in semicircles. 
... 

// 
// Prints the angle to the output stream as "x°" in degrees 
void Angle::output(std::ostream& out) const 
{ 
    out << getDegrees() << "°"; 
} 
+1

是否有一个包含的ostream&operator <<(ostream&,char *)或ostream&operator <<(ostream&,string&)?在这种情况下,编译器无法在其中包含一个模板和模板 ostream&operator <<(ostream,T&)之间进行选择,它们都适用。 – 2012-07-19 19:05:01

+2

您可以为** all **类型定义'operator <<'。显然它与'operator <<'已经为'std :: string'等一些类型定义了冲突。 – 2012-07-19 19:05:20

+0

感谢您的解释。 – 2012-07-19 19:10:50

回答

1

这是因为你在超负荷运营商< <使用模板,但这种过载不上课,所以你不能设置类型名ŧ 。换句话说,对于每个你想使用的变量类型,你必须重载运算符< <,或者在类中重载这个运算符,这也是一个模板。例如:

std::ostream& operator<<(std::ostream& out, const Angle& x) 
{ 
    x.output(out); 

    return out; 
} 

此错误意味着编译器无法预测将在那里使用哪种类型的变量。


你重载这个操作符的所有可能的数据,所以当你通过getDegrees()函数,该函数返回双的话,我不认为x.output(出); (提示x将会加倍)

+0

正在使用模板,因为此重载将用于传递给它的多个不同变量。此代码也是遗留代码,稍微更新,所以我知道这是过去的工作,但现在它不会。 – 2012-07-19 19:05:20

+1

你为所有可能的数据重载这个运算符,所以当你传递getDegrees()函数,返回double时,我不认为x.output(out);将工作;)(提示x将会加倍) – Blood 2012-07-19 19:08:04