用友元加法运算符重载异或加密
时间: 2023-07-09 08:05:09 浏览: 55
首先,我们定义一个类`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`函数,输出了加密后的结果。