我收到此操作员重载错误。下面是我得到的错误:重载<<操作员错误
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() << "°";
}
是否有一个包含的ostream&operator <<(ostream&,char *)或ostream&operator <<(ostream&,string&)?在这种情况下,编译器无法在其中包含一个模板和模板 ostream&operator <<(ostream,T&)之间进行选择,它们都适用。 –
2012-07-19 19:05:01
您可以为** all **类型定义'operator <<'。显然它与'operator <<'已经为'std :: string'等一些类型定义了冲突。 – 2012-07-19 19:05:20
感谢您的解释。 – 2012-07-19 19:10:50