我收到此操作員重載錯誤。下面是我得到的錯誤:重載<<操作員錯誤
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