2012-07-19 89 views
2

我收到此操作員重載錯誤。下面是我得到的錯誤:重載<<操作員錯誤

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

是否有一個包含的ostream&operator <<(ostream&,char *)或ostream&operator <<(ostream&,string&)?在這種情況下,編譯器無法在其中包含一個模板和模板 ostream&operator <<(ostream,T&)之間進行選擇,它們都適用。 – 2012-07-19 19:05:01

+2

您可以爲** all **類型定義'operator <<'。顯然它與'operator <<'已經爲'std :: string'等一些類型定義了衝突。 – 2012-07-19 19:05:20

+0

感謝您的解釋。 – 2012-07-19 19:10:50

回答

1

這是因爲你在超負荷運營商< <使用模板,但這種過載不上課,所以你不能設置類型名ŧ 。換句話說,對於每個你想使用的變量類型,你必須重載運算符< <,或者在類中重載這個運算符,這也是一個模板。例如:

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

    return out; 
} 

此錯誤意味着編譯器無法預測將在那裏使用哪種類型的變量。


你重載這個操作符的所有可能的數據,所以當你通過getDegrees()函數,該函數返回雙的話,我不認爲x.output(出); (提示x將會加倍)

+0

正在使用模板,因爲此重載將用於傳遞給它的多個不同變量。此代碼也是遺留代碼,稍微更新,所以我知道這是過去的工作,但現在它不會。 – 2012-07-19 19:05:20

+1

你爲所有可能的數據重載這個運算符,所以當你傳遞getDegrees()函數,返回double時,我不認爲x.output(out);將工作;)(提示x將會加倍) – Blood 2012-07-19 19:08:04