注册 登录
编程论坛 C++教室

小白求助 模板类中友元函数重载<<运算符 应该怎么写?

d7se123 发布于 2020-05-14 11:36, 1613 次点击
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;
}
这样写报错 模板类中友元函数重载<<运算符 应该怎么写?
1 回复
#2
rjsp2020-05-14 12:49
你这代码缺的也太多了吧,
“模板类中……”哪里有模板类?“c.a……c.b”哪里有a、b?

程序代码:
#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;
}

1