如何使用提取运算符从C ++中的类方法获取多个值?

弱煎排

就像我们在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:我知道其他方法,但是我想知道这种特定的方法,谢谢。

迪特玛·库尔(DietmarKühl)

您定义的插入运算符可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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在继承的类上使用运算符重载以匹配C#中的基本运算符

无法在 C++ 中重载流提取运算符 (>>)

C ++中的重载流提取运算符

在 C++ 中重载流提取运算符 (>>) 的运算符会导致无限递归流提取

如何对多个值使用LIKE运算符

如何使用模运算符获取逆时针值?

如何在 C++ 中的类中使用运算符重载函数?

使用模板类在C ++中重载运算符

Javascript - 如何使用 AND (&&) 运算符获取 if 条件中的键值

如何使用wasm中的<>运算符评估js值?

如何使用 '!运算符”和TypeScript中的“ in运算符”?

为什么“ as”运算符在C#中不使用隐式转换运算符?

如何使用从数据库中提取并添加到PHP脚本中的条件运算符

我将如何为这个使用数组的 bigint 类重载 + 运算符?C++

C ++中的运算符:如何使用C ++中的运算符将内部对象中的变量值分配给int变量

对多个值使用运算符+ =

如何在C ++中使用编译时三元运算符获取对象成员

如何在C#中使用=>运算符作为get访问器的返回值

c ++如何将constexpr值与运算符[]一起使用

+ = C ++中的运算符

C中的||,&&运算符

C#如何检查null。(值是null)或(空==值)。我们可以使用`is`运算符代替==运算符吗

C ++如何创建双重类运算符[] []

与C ++中存在的C#中的提取/插入运算符重载类似的替代方法

如何在C中的条件运算符中使用0?

在C ++中如何在const unordered_map上使用“ []”运算符来解决?

如何使用Roslyn在C#中添加新运算符

如何使用按位运算符和位操作在C中交换2个整数?

新运算符如何与C#中的委托一起使用