0

就像我们在 cin 中使用的那样:

cin >> a >> b;

从输入流中获取多个值并将它们插入到多个变量中。我们如何在自己的类中实现这个方法?从中获取多个值。我尝试了这个发现here

#include <iostream>
using namespace std;

class example {
    friend istream& operator>> (istream& is, example& exam);
    private:
        int my = 2;
        int my2 = 4;
};

istream& operator>> (istream& is, example& exam) {
    is >> exam.my >> exam.my2;
    return is;  
}

int main() {
    example abc;
    int s, t;

    abc >> s >> t;
    cout << s << t;
}

但是出现错误“与运算符不匹配>>(操作数类型为'example'和'int')”

PS:我知道其他方法,但我想知道这种具体的方法,谢谢。

4

2 回答 2

1

You want to extract data from an example into an int. Instead, you wrote code to extract data from an istream into an example. That's why the right function cannot be found: you did not write one.

If you really wish to allow abc >> s >> t to work, you're going to have to define an operator>>(example&, int&) and add stream/cursor semantics to your class, to keep track at each step of what's been extracted so far. That really sounds like more trouble than it's worth.

于 2016-12-28T17:51:41.107 回答
0

您定义的插入运算符std::istream用作源而不是您自己的类。尽管我认为您的目标不明智,但您可以为您的班级创建类似的运算符。您需要一些具有合适状态的实体,因为链式运算符应该提取不同的值。

我不会将它用于任何类型的生产设置,但它肯定可以完成:

#include <iostream>
#include <tuple>
using namespace std;

template <int Index, typename... T>
class extractor {
    std::tuple<T const&...> values;
public:
    extractor(std::tuple<T const&...> values): values(values) {}
    template <typename A>
    extractor<Index + 1, T...> operator>> (A& arg) {
        arg = std::get<Index>(values);
        return extractor<Index + 1, T...>{ values };
    }
};

template <typename... T>
extractor<0, T...> make_extractor(T const&... values) {
    return extractor<0, T...>(std::tie(values...));
}

class example {
private:
    int my = 2;
    int my2 = 4;
    double my3 = 3.14;
public:
    template <typename A>
    extractor<0, int, double> operator>> (A& arg) {
        arg = my;
        return make_extractor(this->my2, this->my3);
    }
};

int main() {
    example abc;
    int s, t;
    double x;

    abc >> s >> t >> x;
    cout << s << " " << t << " " << x << "\n";
}
于 2016-12-28T18:06:36.160 回答