【问题标题】:Is it possible to use the class object as a value? [duplicate]是否可以将类对象用作值? [复制]
【发布时间】:2016-06-19 12:33:30
【问题描述】:

我不知道我所问的编程术语(这对我来说是个爱好),我在这里尝试新事物。查看我的工作场景:

#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;
}

【问题讨论】:

  • yes 尝试查找重载流插入操作符
  • 好的,知道了,谢谢:)
  • 请重新考虑您对endl 的使用。 (虽然 +1 不是 using namespace std;)。
  • 仅在.cpp 实现文件中使用using namespace std;,但在.h 头定义文件中更新
  • 你试过了吗?它奏效了吗?见minimal reproducible example。

标签: c++


【解决方案1】:

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

#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;
}

【讨论】:

  • 一个好的答案应该解释如何做某事,而不仅仅是链接到其他地方。外部链接可能会失效,无法访问等。对于 SO 上的链接,问题应该作为其中一个的副本关闭。
  • 谢谢,答案改进了
猜你喜欢
  • 2018-04-17
  • 1970-01-01
  • 2016-11-28
  • 2021-02-25
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
相关资源
最近更新 更多