输出操作符重载

来源:互联网 发布:网络银行是什么 编辑:程序博客网 时间:2024/05/22 07:57

operator<<()重载的例子:

#include <iostream>class Something {public:    explicit Something(int v) : _v(v) {}    int getValue() const { return _v; }private:    Something();private:    int _v;};std::ostream& operator<<(std::ostream &os, const Something& something){    os << something.getValue() << '\t';    return os;}int main(){    Something something(1);    std::cout << something << std::endl;    return 0;}

在operator<<()的重载时,需要注意入参和返回值均数引用类型。——因为ostream基类中的构造函数是protected类型,所以不能直接传对象或返回对象,必须是对象的引用。


0 0
原创粉丝点击