2

我在此运算符重载上遇到错误。这是我得到的错误:

Angle.cpp:466: 错误:'(+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()字符串而是来自字符串。我尝试将字符串更改为“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() << "°";
}
4

1 回答 1

1

这是因为你在重载的 operator<< 中使用了模板,但这个重载不在类中,所以你不能设置 typename T。换句话说,你必须为你想要的每种类型的变量重载 operator<<在也是模板的类中使用或重载此运算符。例如:

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

    return out;
}

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


您为所有可能的数据重载此运算符,因此当您传递返回 double 的 getDegrees() 函数时,我不认为 x.output(out); 会工作;)(提示 x 将是双倍的)

于 2012-07-19T19:00:50.437 回答