| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1310 人关注过本帖
标题:小白求助 模板类中友元函数重载<<运算符 应该怎么写?
只看楼主 加入收藏
d7se123
Rank: 2
等 级:论坛游民
帖 子:65
专家分:14
注 册:2020-3-13
结帖率:50%
收藏
 问题点数:0 回复次数:1 
小白求助 模板类中友元函数重载<<运算符 应该怎么写?
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;
}
这样写报错 模板类中友元函数重载<<运算符 应该怎么写?
搜索更多相关主题的帖子: out 类中 运算符 友元 函数重载 
2020-05-14 11:36
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:0 
你这代码缺的也太多了吧,
“模板类中……”哪里有模板类?“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;
}

2020-05-14 12:49
快速回复:小白求助 模板类中友元函数重载<<运算符 应该怎么写?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014464 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved