搞定运算符之异或^

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们定义一个类`XorEncrypt`,其中包含一个私有成员`std::string str`,表示待加密的字符串。然后,我们需要重载加法运算符`+`和异或运算符`^`。 为了能够在加密函数中访问`XorEncrypt`类的私有成员`str`,我们需要使用友元函数。因此,我们将加法运算符重载函数和异或运算符重载函数声明为`XorEncrypt`类的友元函数。 具体实现如下: ```c++ #include <iostream> #include <string> class XorEncrypt { public: XorEncrypt(const std::string& s) : str(s) {} friend XorEncrypt operator+(const XorEncrypt& e1, const XorEncrypt& e2); friend XorEncrypt operator^(const XorEncrypt& e1, const XorEncrypt& e2); void print() { std::cout << str << std::endl; } private: std::string str; }; XorEncrypt operator+(const XorEncrypt& e1, const XorEncrypt& e2) { return XorEncrypt(e1.str + e2.str); } XorEncrypt operator^(const XorEncrypt& e1, const XorEncrypt& e2) { std::string result = ""; for (int i = 0; i < e1.str.length(); i++) { result += (char)(e1.str[i] ^ e2.str[i % e2.str.length()]); } return XorEncrypt(result); } int main() { XorEncrypt e1("hello"); XorEncrypt e2("world"); XorEncrypt e3 = e1 + e2; e3.print(); XorEncrypt e4 = e1 ^ e2; e4.print(); return 0; } ``` 在上述代码中,我们首先定义了`XorEncrypt`类,并在其中定义了一个私有成员`std::string str`,表示待加密的字符串。然后我们重载了加法运算符`+`和异或运算符`^`,并将它们声明为`XorEncrypt`类的友元函数。 在`operator+`函数中,我们通过对两个`XorEncrypt`对象的`str`成员进行拼接,得到一个新的`XorEncrypt`对象。 在`operator^`函数中,我们对两个`XorEncrypt`对象的`str`成员进行逐个异或运算,并将结果存入一个新的字符串中。需要注意的是,为了让两个字符串的长度相同,我们将`e2.str`的长度作为循环的次数取模,以保证可以对`e1.str`的每个字符都进行异或运算。 最后,在`main`函数中,我们创建了两个`XorEncrypt`对象`e1`和`e2`,并使用加法运算符异或运算符对它们进行了运算,得到了两个新的`XorEncrypt`对象`e3`和`e4`。然后我们分别调用了它们的`print`函数,输出了加密后的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值