【问题标题】:Overloading << operator error重载 << 运算符错误
【发布时间】:2012-07-19 18:52:25
【问题描述】:

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

Angle.cpp:466: 错误:'operatorstd::basic_ostream<_elem _traits>::operatorAngle:: getDegrees())

这是我的类来重载&lt;&lt; 运算符

#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() << "°";
}

【问题讨论】:

  • 难道没有包含 ostream& operator ostream& operator
  • 您为所有类型定义operator&lt;&lt;。显然它与 operator&lt;&lt; 冲突,后者已经为某些类型定义,例如 std::string
  • @n.m.我希望能够再次提出这个问题,但现在有了更好的理解。当我第一次问它时,我不明白这个问题,也无法理解我得到的答案。

标签: c++ operator-overloading


【解决方案1】:

这是因为你在重载的 operator

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

    return out;
}

这个错误意味着编译器无法预测那里将使用什么样的变量。


你为所有可能的数据重载了这个操作符,所以当你传递 getDegrees() 函数时,它返回 double 然后我不认为 x.output(out);会工作;)(提示 x 将是双倍的)

【讨论】:

  • 正在使用模板,因为此重载将用于传递给它的多个不同变量。这段代码也是遗留代码,正在略微更新,所以我知道这在过去有效,但现在不行了。
  • 你为所有可能的数据重载了这个操作符,所以当你传递 getDegrees() 函数时,它返回 double 然后我不认为 x.output(out);会工作;)(提示 x 将是双倍的)
猜你喜欢
  • 2013-11-14
  • 2016-10-18
  • 1970-01-01
  • 2017-08-10
  • 2015-07-04
  • 1970-01-01
  • 2018-07-19
  • 1970-01-01
相关资源
最近更新 更多