就像我们在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;
}
但是得到错误“与运算符不匹配&gt;&gt;(操作数类型是'example'和'int')”
PS:我知道其他方法,但我想知道这种做法的具体方式,谢谢。
答案 0 :(得分:1)
您想要将<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test-div">
Pie jelly-o chocolate sweet topping jujubes tiramisu cupcake kitkat muffin biscuit. Sesame snaps jelly <a href="#" data-tooltip-title="demo text for custom tooltip #1">halvah caramels macaroon</a> powder cake sweet. Toffee jelly-o halvah. Muffin cake macaroon wafer.
Chocolate carrot cake chupa chups. Soufflé candy canes cake. Toffee soufflé sweet roll fruitcake sesame snaps brownie jelly-o. Marshmallow dessert biscuit topping gummies gummi bears ice cream cookie
<br>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur eum ducimus optio nesciunt <a href="#" data-tooltip-title="demo text for custom tooltip #2">porro delectus </a>nam ipsam voluptatem eaque, tempore voluptates enim? Maxime amet quas
unde eligendi recusandae esse cum?
</div>
<div id="my-tooltip"></div>
中的数据提取到example
。相反,您编写了代码以将int
中的数据提取到istream
中。这就是为什么找不到合适的功能的原因:你没有写一个。
如果您真的希望允许example
工作,您将需要定义abc >> s >> t
并向您的班级添加流/游标语义,以便跟踪每个步骤到目前为止已经提取了什么。这真的听起来比它的价值更麻烦。
答案 1 :(得分: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";
}