| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1387 人关注过本帖
标题:关于赋值运算符程序的bug
只看楼主 加入收藏
小小南瓜
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2017-1-20
结帖率:0
收藏
已结贴  问题点数:20 回复次数:2 
关于赋值运算符程序的bug
求问大神为什么最后那个输出运算符会报错呢?是我重载的输出运算符不对吗?应该怎么改求指点

程序代码:
#include<iostream>
using namespace std;
template<class T>
struct Bestandteil
{
    Bestandteil(const T& t) :t_(t){}
    Bestandteil& operator=(const Bestandteil& b)
    {
        cout << "Zuweisung von " << b.t_ << "ersetzt" << t_ << endl;
        t_ = b.t_;
        return *this;
    }
    T t_;
};
class Test
{
public:
    Test(int i, double d, char* c) :i_(i), d_(d), c_(c){}
    virtual void ausgeben(ostream& os)const
    {
        os << i_.t_ << '\t' << d_.t_ << '\t' << c_.t_;
    }
private:
    Bestandteil<int> i_;
    Bestandteil<double> d_;
    Bestandteil<char*> c_;
};
void main()
{
    Test t1(1, 22.0 / 7, "Halli"),
        t2(2, 2.0 * 22 / 7, "Hallo");
    cout << t1 << endl << t2 << endl;   //此处第一个输出运算符报错
    t1 = t2;
    cout <<t1 << endl << t2 << endl;

}
2017-01-20 23:06
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:10 
为什么不贴出编译器给出的错误信息呢?
cout << t1 << endl << t2 << endl; 报错 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Test' (or there is no acceptable conversion)


程序代码:
class Test
{
public:
    Test(int i, double d, char* c) :i_(i), d_(d), c_(c){}
private:
    Bestandteil<int> i_;
    Bestandteil<double> d_;
    Bestandteil<char*> c_;

    friend std::ostream& operator<<( std::ostream& os, const Test& t );
};
std::ostream& operator<<( std::ostream& os, const Test& t )
{
    return os << t.i_.t_ << '\t' << t.d_.t_ << '\t' << t.c_.t_;
}

2017-01-22 08:27
ml232528
Rank: 8Rank: 8
等 级:蝙蝠侠
威 望:5
帖 子:367
专家分:879
注 册:2007-7-23
收藏
得分:10 
<< 只是一个运算符。标准库只重载了基础类型,以及一些常用的类型。Test类型在编写标准库时,并不存在, ostream<< test 需要自己实现。像二楼那样。

-︻┻┳═一 ☆ 悲伤的代价就是让自己明白什么是最重要的和应该珍惜的
2017-01-22 11:01
快速回复:关于赋值运算符程序的bug
数据加载中...
 
   



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

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