小白求助 模板类中友元函数重载<<运算符 应该怎么写?
class Complex{
public:
friend ostream& operator<<(ostream& out,Complex& c);
}
//类外
ostream& operator<<(ostream& out,Complex<T>& c)
{
out<<c.a<<" "<<c.b<<endl;
return out;
}
这样写报错 模板类中友元函数重载<<运算符 应该怎么写?
2020-05-14 11:36
程序代码:#include <iostream>
template<typename T>
class Complex
{
public:
Complex( const T& real=T(), const T& image=T() ) noexcept : real_(real), image_(image)
{
}
private:
T real_, image_;
template<typename U> friend std::ostream& operator<<( std::ostream& out, const Complex<U>& c );
};
template<typename U>
std::ostream& operator<<( std::ostream& out, const Complex<U>& c )
{
out << c.real_;
std::ios::fmtflags save = out.setf( std::ios::showpos );
out << c.image_ << 'i';
out.setf( save );
return out;
}
using namespace std;
int main( void )
{
std::cout << Complex(1.2,+5.6) << std::endl;
std::cout << Complex(1.2,-5.6) << std::endl;
}
2020-05-14 12:49