我在此操作员过载时收到错误。这是我得到的错误:
Angle.cpp:466:错误:'operator<<'的模糊重载在 '(+ out) - > std :: basic_ostream< _Elem,_Traits> :: operator<< [与 _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()
而是来自字符串。我尝试将字符串更改为“hello”,以确保它不是符号,但我收到了同样的错误。
以下是不包含无关代码的其余代码:
// 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() << "°";
}
答案 0 :(得分:1)
这是因为你在重载的运算符&lt;&lt;中使用了模板,但是这个重载不在类中,所以你不能设置typename T.换句话说,你必须重载operator&lt;&lt;对于您想要使用的每种类型的变量,或者在类中重载此运算符(也是模板)。例如:
std::ostream& operator<<(std::ostream& out, const Angle& x)
{
x.output(out);
return out;
}
此错误意味着编译器无法预测将在那里使用哪种变量。
你为所有可能的数据重载此运算符,所以当你传递getDegrees()函数时,返回double然后我不认为x.output(out);将工作;)(提示x将是双倍)