就像我们在cin中使用的一样:
cin >> a >> b;
从输入流中获取多个值并将其插入到多个变量中。我们如何在自己的类中实现此方法?从中获取多个值。我尝试了这个,在这里找到:
#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:我知道其他方法,但是我想知道这种特定的方法,谢谢。
您定义的插入运算符可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";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句