【发布时间】:2018-07-28 05:27:58
【问题描述】:
让我告诉你们,我是 C++ 的初学者。
出于教育和学习的目的,我创建了自己的字符串类,名为MyString。根据我的导师的指示,我不允许使用标准库函数来比较两个字符串。
MyString 类包含 char 类型指针和保存字符串长度的整数类型变量,即:
class MyString{
char *str; int len;
public:
MyString(){
len = 1;
str = new char[len];
str[len - 1] = '\0';
}
MyString(char *p){
int count = 0;
for (int i = 0; p[i] != '\0'; i++){
count++;
}
len = count;
str = new char[len];
for (int i = 0; i < len; i++){
str[i] = p[i];
}
}
int length(){
return len;
}
bool operator < (MyString obj){
char temp;
if (len < obj.len){ return true; }
if (len>obj.len){ return false; }
if (this->len == obj.len){
for (int i = 0; i < len; i++){
if (this->str[i] < obj.str[i])
{
return true;
}
}
}
}
bool operator > (MyString obj) {
if (len > obj.len) {
return true;
}
if (len<obj.len) {
return false;
}
if (this->len == obj.len)
{
for (int i = 0; i < this->len; i++) {
if (this->str[i] > obj.str[i]) {
return true;
}
}
}
}
bool operator == (MyString obj) {
int count = 0;
if (this->len == obj.len){
for (int i = 0; i < this->len; i++) {
if (this->str[i] == obj.str[i]) {
count++;
}
}
if (count == len) {
return true;
}
}
}
char & operator[](int i) {
return str[i];
}
};
这里是主要的
int main()
{
char arr1[30], arr2[30];
cout << "Enter first MyString: ";
cin.get(arr1, 30);
cin.ignore();
cout << "Enter second MyString: ";
cin.get(arr2, 30);
MyString s1(arr1); //parametrized constructor
MyString s2(arr2);
cout << "Length of s1:" << s1.length() << endl;
cout << "Length of s2:" << s2.length() << endl;
if (s1<s2) // < operator overloaded
cout << "s1 < s2" << endl;
else if (s1>s2) // > operator overloaded
cout << "s1 > s2" << endl;
else if (s1 == s2) // == operator overloaded
cout << "s1 == s2" << endl;
return 0;
}
我比较两个字符串的算法是:
i).首先检查两个字符串的长度,如果 len(length of s1) 小于 obj.len(length of s2) 则返回 true。
ii).如果长度相等,则将 s1 char 数组的每个元素与 s2 char 数组进行比较。即使 s1 char 数组的元素之一小于 s2 char 数组元素(ASCII 格式),则返回 true 否则返回假的。
问题是每当程序执行时,无论传递的两个字符串是否相等,在控制台上都会显示“s1
【问题讨论】:
-
请不要包含不相关语言的标签。这不是 C。
-
bool operator < (MyString obj){-- 我猜你的导师从未提到过“3 规则”。那一行代码可能会引入双重删除错误和内存损坏。此外,如果您要学习自己的字符串课程,至少老师应该给您一个真正有效的课程,而不是充满内存泄漏和错误的课程。 -
题外话:不要使用
if来检查先前如果:if(condition) if(!condition)(坏)或变体:if(condition) else if(!condition)的补码。只需简单的 else 代替:if(condition) else;也适用于您的相等检查,如果 都不适用,则相等 确实 适用,因此:if(<) else if(>) else(不再需要==- 除非您有可能导致两者都不是的比较 也不 ==)。 -
真正的问题是尝试创建对初学者来说似乎很容易弄清楚如何创建的类,但正确创建却不是那么明显。您的类缺少析构函数,因此存在内存泄漏。如果您添加析构函数,那么按值传递
MyString的那行代码现在会导致内存损坏等。 -
我建议您学习如何在编译时启用警告。有些功能无法返回他们承诺的内容。这应该会生成一个警告来帮助您修复代码。另外,请阅读minimal reproducible example,如果您只是对
operator==有问题,则应该删除任何不必要的内容。
标签: c++ string memory-management operator-overloading