是否可以将类对象用作值?

时间:2016-03-05 19:17:25

标签: c++

我不知道我要问的问题(这对我来说是业余爱好)的术语,我在这里尝试新事物。看我的工作场景:

#include <iostream>

class Foo {
    int _x;
    public:
        Foo () : _x(0) {}
        Foo (int x) : _x(x) {}
        int get () const { return _x; }
};

int main () {
    Foo f1;
    Foo f2(10);
    std::cout << "Value: " << f1.get () << std::endl; // 0
    std::cout << "Value: " << f2.get () << std::endl; // 10
    return 0;
}

是否可以像这样使用f1或f2:

std::cout << "Value: " << f2 << std::endl; // shows 10

使用正确的代码更新

#include <iostream>

class Foo {
    int _x;
    public:
        Foo () : _x(0) {}
        Foo (int x) : _x(x) {}
        int get () const { return _x; }
        friend std::ostream &operator<<(std::ostream &os, const Foo& f) { 
            return os << f.get ();
        }
};

int main () {
    Foo f1;
    Foo f2(10);
    std::cout << "Value: " << f1.get () << '\n'; // 0
    std::cout << "Value: " << f2.get () << '\n'; // 10
    std::cout << "Value: " << f1 << '\n'; // 0
    return 0;
}

1 个答案:

答案 0 :(得分:2)

是的,这是重载流插入运算符。

#include <iostream>

class Foo {
    int _x;
    public:
        Foo () : _x(0) {}
        Foo (int x) : _x(x) {}
        int get () const { return _x; }
        friend std::ostream& operator<< ( std::ostream& stream, const Foo& foo );
};

std::ostream& operator<< ( std::ostream& stream, const Foo& foo ) {
    stream << foo._x;
    return stream;
}

int main () {
    Foo f1;
    Foo f2(10);
    std::cout << "Value: " << f1 << std::endl; // 0
    std::cout << "Value: " << f2 << std::endl; // 10
    return 0;
}