c++字符串运算符重载代码
下面是一个简单的C++字符串运算符重载代码示例:
#include <iostream>
#include <string>
using namespace std;
class myString {
private:
string str;
public:
myString() {
str = "";
}
myString(string s) {
str = s;
}
myString operator+(myString& s) {
myString result;
result.str = str + s.str;
return result;
}
bool operator==(myString& s) {
if (str == s.str) {
return true;
}
else {
return false;
}
}
bool operator!=(myString& s) {
if (str != s.str) {
return true;
}
else {
return false;
}
}
void print() {
cout << str << endl;
}
};
int main() {
myString s1("Hello");
myString s2("World");
myString s3("Hello");
myString s4 = s1 + s2;
s4.print();
if (s1 == s2) {
cout << "s1 is equal to s2" << endl;
}
else {
cout << "s1 is not equal to s2" << endl;
}
if (s1 == s3) {
cout << "s1 is equal to s3" << endl;
}
else {
cout << "s1 is not equal to s3" << endl;
}
if (s1 != s2) {
cout << "s1 is not equal to s2" << endl;
}
else {
cout << "s1 is equal to s2" << endl;
}
if (s1 != s3) {
cout << "s1 is not equal to s3" << endl;
}
else {
cout << "s1 is equal to s3" << endl;
}
return 0;
}
这个例子中,我们定义了一个名为myString的类,它包含一个私有成员变量str,代表字符串。我们重载了+、==和!=运算符,以便我们可以使用这些运算符对myString对象进行操作。
在主函数中,我们创建了三个myString对象s1、s2和s3,并对它们进行了一些运算符重载操作。最后输出了运算结果
原文地址: https://www.cveoy.top/t/topic/eEwc 著作权归作者所有。请勿转载和采集!