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

关于赋值运算符程序的bug

小小南瓜 发布于 2017-01-20 23:06, 1389 次点击
求问大神为什么最后那个输出运算符会报错呢?是我重载的输出运算符不对吗?应该怎么改求指点

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

}
2 回复
#2
rjsp2017-01-22 08:27
为什么不贴出编译器给出的错误信息呢?
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_;
}

#3
ml2325282017-01-22 11:01
<< 只是一个运算符。标准库只重载了基础类型,以及一些常用的类型。Test类型在编写标准库时,并不存在, ostream<< test 需要自己实现。像二楼那样。
1