当前位置: 代码迷 >> 综合 >> C++ day20 用动态内存开发类 (二)为字符串对象重载一系列运算符
  详细解决方案

C++ day20 用动态内存开发类 (二)为字符串对象重载一系列运算符

热度:65   发布时间:2024-02-04 20:03:50.0

本文将对上一篇文章的StringBad类进一步添砖加瓦,主要是添加更多的类方法,使得这个类具有更多的功能,主要涉及到返回字符串长度方法,比较两个字符串的大小(字符编码大小)的方法,重载抽取运算符以从输入字节流获取输入,静态类方法,重载数组下标运算符以返回某一个字符。

相比于C++提供的标准string类,这些还差得很远,但是相比于上文StringBad类的错误百出,起码这个类是正确的,且有更多功能。

文章目录

  • 对上一篇文章的StringBad类进一步添砖加瓦,使用对象数组
    • 测试运算符<, >, == ,= 和输入>>
    • 测试[]运算符和静态成员函数
      • 静态类成员函数
      • 默认构造函数中使用空指针
      • 构造和析构的new和delete注意事项总结

对上一篇文章的StringBad类进一步添砖加瓦,使用对象数组

很多方法都是自己写的,还是很不错的

//StringBad.h
#include <iostream>
#ifndef STRINGBAD_H_
#define STRINGBAD_H_
typedef unsigned int uint;class StringBad{
private:char * str;//指针成员,不再用char数组,而用char指针,只存储地址,用new分配uint strLen;static uint numStrings;//静态类成员示例,仅作示例,实际string类无需这个成员static const uint CINLIM = 80;//只有静态const成员可以在类声明中初始化
public:StringBad();StringBad(const char * st);//不要把构造函数声明为const成员函数StringBad(const StringBad & st);//显式的自定义复制构造函数~StringBad();StringBad & operator=(const StringBad & st);//显式的自定义赋值运算符函数StringBad & operator=(const char *);//重载赋值运算符函数,参数可以是数组名uint length() const {return strLen;}//内联函数char & operator[](uint i) {return *(str + i);}//return *(str + i);和return str[i];一样//对于const对象,char & operator[](uint i)是会报错的,所以必须专门再定义一个,且const对象的单个字符也必须是const的const char & operator[](uint i) const {return str[i];}friend std::ostream & operator<<(std::ostream & os, const StringBad & st);friend bool operator<(const StringBad & st1, const StringBad & st2);friend bool operator>(const StringBad & st1, const StringBad & st2);friend bool operator==(const StringBad & st1, const StringBad & st2);friend std::istream & operator>>(std::istream & is, StringBad & st);//用到常量CINLIM//静态成员函数static uint HowMany() {return numStrings;}
};#endif
//stringBad.cpp
#include <iostream>
#include <cstring>
#include "StringBad.h"
typedef unsigned int uint;
void eatline();//在方法文件初始化静态类成员,不可在头文件的类声明中初始化,因为:
//第一,类声明只说明如何分配内存,并不实际分配内存
//第二,如果写在头文件,如果程序的多个源文件都包含了该头文件,则静态类成员的初始化语句将有多条,会引发错误
//且这里无需使用static
//静态类成员不是对象的组成部分,不存储在对象里,而是存在静态内存中,所以也无需在类作用域中初始化
uint StringBad::numStrings = 0;StringBad::StringBad()
{strLen = 0;str = new char[strLen + 1];std::strcpy(str, "");++numStrings;std::cout << numStrings << ": default object created!\n";
}StringBad::StringBad(const char * st)
{strLen = std::strlen(st);str = new char[strLen + 1];std::strcpy(str, st);//由于是分配的刚好的内存,不用担心内存覆盖的安全问题++numStrings;std::cout << numStrings << ": \"" << str << "\" object created!\n";
}StringBad::StringBad(const StringBad & st)
{++numStrings;//深复制strLen = std::strlen(st.str);str = new char[strLen + 1];std::strcpy(str, st.str);std::cout << "explicit copy constructor called.\n";std::cout << numStrings << ": " << str << " object created!\n";
}
StringBad::~StringBad()
{--numStrings;std::cout << "\"" << str << "\" object deleted! " << numStrings << " objects left!\n";delete [] str;
}StringBad & StringBad::operator=(const StringBad & st)
{//首先禁止源和目标对象是同一个对象的情况,我没想到用地址判断if (this == &st)return *this;strLen = st.strLen;delete [] str;//我忘了!!!!!str = new char[strLen + 1];std::strcpy(str, st.str);std::cout << "explicit assignment operator called (using deep copy)!\n";return *this;//我忘了。。
}StringBad & StringBad::operator=(const char * st)
{strLen = std::strlen(st);str = new char[strLen + 1];std::strcpy(str, st);return *this;//我忘记写返回语句。。。
}std::ostream & operator<<(std::ostream & os, const StringBad & st)
{os << st.str;//我竟然没写.str。。。。return os;
}bool operator<(const StringBad & st1, const StringBad & st2)
{//复杂版//return (std::strcmp(st1.str, st2.str) < 0) ? true : false;//简洁版return (std::strcmp(st1.str, st2.str) < 0);
}bool operator>(const StringBad & st1, const StringBad & st2)
{//复杂版//return (std::strcmp(st1.str, st2.str) > 0) ? true : false;//简洁版,立马重用代码,智慧啊return (st2 < st1);
}bool operator==(const StringBad & st1, const StringBad & st2)
{//简洁版return (std::strcmp(st1.str, st2.str) == 0);//复杂版//return (std::strcmp(st1.str, st2.str) == 0) ? true : false;
}std::istream & operator>>(std::istream & is, StringBad & st)
{delete [] st.str;//忘记st.//释放目标对象的指针成员指向的地址,否则会内存泄漏//由于输入到st.str之前要先给st.str动态分配内存,所以必须给定长度,所以新增了静态类成员CINLIM//另外,由于<<遇到空白符就罢工,所以应该用cin.get(char *, int)方法,且用一个数组做输入缓冲char temp[StringBad::CINLIM];//忘记StringBad::if (is.get(temp, StringBad::CINLIM)){st = temp;//使用重载赋值运算符,实现了代码重用//*this = temp;//StringBad & operator=(const char * st);竟在友元函数中用起了this!!!/*//不重用代码就写这个复杂版st.strLen = std::strlen(temp);st.str = new char[st.strLen + 1];std::strcpy(st.str, temp);*/}elseis.clear();//清除错误标记,错写为is.std::clear(),clear()方法不在名称空间std???eatline();//清空输入缓存std::cout << "Enter friend function: operator>>\n";return is;
}void eatline()
{while (std::cin.get() != '\n');
}

测试运算符<, >, == ,= 和输入>>

重载<<和>>运算符必须要用friend function,因为第一个参数不能是调用对象,而是ostream类对对象和istream类对象。

//main.cpp
#include <iostream>
#include "StringBad.h"
void eatline();
typedef unsigned int uint;
const uint ARSIZE = 10;int main()
{{using std::cout;using std::cin;cout << "starting an inner block\n";StringBad sayings[ARSIZE];//默认构造函数cout << "Enter up to " << ARSIZE << " sayings (empty line to quit):\n>>";//输入提示符,很棒棒uint i;for (i = 0; i < ARSIZE; ++i){if (!(cin >> sayings[i]) || sayings[i][0] == '\0')break;}if (i > 0){cout << "Here is the " << i << " sayings:\n";uint j;uint shortest = 0, first = 0;for (j = 0; j < i; ++j){cout << sayings[j][0] << ": " << sayings[j] << '\n';if (sayings[j] < sayings[first])first = j;if (sayings[j].length() < sayings[shortest].length())//我又错误地写成sayings[j].strLen < sayings[shortest].strLenshortest = j;}cout << "The shortest saying: " << sayings[shortest] << '\n';cout << "The first saying alphabetically: " << sayings[first] << '\n';}elsecout << "No sayings entered!\n";}std::cout << "Exiting the main() function\n";return 0;
}

我故意没有删除构造函数,析构函数发送的消息,还在输入运算符的友元函数中添加了消息,可以看到,数组大小为10,如果只输入5个对象,其余5个也是会调用构造函数和析构函数的。

starting an inner block
1: default object created!
2: default object created!
3: default object created!
4: default object created!
5: default object created!
6: default object created!
7: default object created!
8: default object created!
9: default object created!
10: default object created!
Enter up to  10 sayings (empty line to quit):
>>a fool and his money are soon parted
Enter friend function: operator>>
penny wise, pound foolish
Enter friend function: operator>>
the love of money is the root of much evil
Enter friend function: operator>>
out of sight, out of mind
Enter friend function: operator>>
absence makes the heart grow fonder
Enter friend function: operator>>Enter friend function: operator>>
Here is the 5 sayings:
a: a fool and his money are soon parted
p: penny wise, pound foolish
t: the love of money is the root of much evil
o: out of sight, out of mind
a: absence makes the heart grow fonder
The shortest saying: penny wise, pound foolish
The first saying alphabetically: a fool and his money are soon parted
"" object deleted! 9 objects left!
"" object deleted! 8 objects left!
"" object deleted! 7 objects left!
"" object deleted! 6 objects left!
"" object deleted! 5 objects left!
"absence makes the heart grow fonder" object deleted! 4 objects left!
"out of sight, out of mind" object deleted! 3 objects left!
"the love of money is the root of much evil" object deleted! 2 objects left!
"penny wise, pound foolish" object deleted! 1 objects left!
"a fool and his money are soon parted" object deleted! 0 objects left!
Exiting the main() function

输入数字也可以的哈,毕竟是字符串,输入啥都行

starting an inner block
1: default object created!
2: default object created!
3: default object created!
4: default object created!
5: default object created!
6: default object created!
7: default object created!
8: default object created!
9: default object created!
10: default object created!
Enter up to  10 sayings (empty line to quit):
>>45
Enter friend function: operator>>
aghf
Enter friend function: operator>>
h
Enter friend function: operator>>Enter friend function: operator>>
Here is the 3 sayings:
4: 45
a: aghf
h: h
The shortest saying: h
The first saying alphabetically: 45
"" object deleted! 9 objects left!
"" object deleted! 8 objects left!
"" object deleted! 7 objects left!
"" object deleted! 6 objects left!
"" object deleted! 5 objects left!
"" object deleted! 4 objects left!
"" object deleted! 3 objects left!
"h" object deleted! 2 objects left!
"aghf" object deleted! 1 objects left!
"45" object deleted! 0 objects left!
Exiting the main() function

出现的错误除了注释里写到的(主要还是访问权限涉及的错误)之外还有:

  • multiple definition of function eatline()错误
    之前写过一个Vector类,矢量,当时在方法文件中定义了eatline()函数,但是vector.cpp一直放在这个项目中,没有删除,于是今天在StringBad.cpp中再次定义eatline函数,就被编译器发现了多重定义,违反了单定义规则,ODR。这是因为这两个方法文件都在这个程序下,所以编译器把两个文件的机器码链接了,发现了两个定义。在这里解决方式是删除不相干的代码文件。

但是在路径下直接删除所有的源代码文件和.o目标文件还是会报错:
在这里插入图片描述

必须在项目中把其他文件remove from the project才可以

测试[]运算符和静态成员函数

//main.cpp
#include <iostream>
#include "StringBad.h"
void eatline();
typedef unsigned int uint;
const uint ARSIZE = 10;int main()
{{using std::cout;using std::cin;cout << "starting an inner block\n";const StringBad name("Mary Chrawly");cout << "The characters are:\n";uint i;for (i = 0; i < name.length(); ++i)cout << name[i] << ' ';//name是const对象,调用cout << '\n';cout << "The program used " << StringBad::HowMany() << " objects.\n";}std::cout << "Exiting the main() function\n";return 0;
}

头文件中两个内联函数,我在这犯了一个低级错误:把输出语句放在了return语句后面!!!怎么都不输出,我还觉得很奇怪呢,,,,,

char & operator[](uint i)
{std::cout << "char & operator[](uint i)\n";return *(str + i);//return *(str + i);和return str[i];一样
}//对于const对象,char & operator[](uint i)是会报错的,所以必须专门再定义一个,且const对象的单个字符也必须是const的
const char & operator[](uint i) const
{std::cout << "const char & operator[](uint i) const\n";return str[i];
}
starting an inner block
1: "Mary Chrawly" object created!
The characters are:
const char & operator[](uint i) const
M const char & operator[](uint i) const
a const char & operator[](uint i) const
r const char & operator[](uint i) const
y const char & operator[](uint i) constconst char & operator[](uint i) const
C const char & operator[](uint i) const
h const char & operator[](uint i) const
r const char & operator[](uint i) const
a const char & operator[](uint i) const
w const char & operator[](uint i) const
l const char & operator[](uint i) const
y
The program used 1 objects.
"Mary Chrawly" object deleted! 0 objects left!
Exiting the main() function

去掉name对象前面的const:

starting an inner block
1: "Mary Chrawly" object created!
The characters are:
char & operator[](uint i)
M char & operator[](uint i)
a char & operator[](uint i)
r char & operator[](uint i)
y char & operator[](uint i)char & operator[](uint i)
C char & operator[](uint i)
h char & operator[](uint i)
r char & operator[](uint i)
a char & operator[](uint i)
w char & operator[](uint i)
l char & operator[](uint i)
y
The program used 1 objects.
"Mary Chrawly" object deleted! 0 objects left!
Exiting the main() function

静态类成员函数

  • 如果定义不在头文件,即不是内联函数,则定义处不能再用static
  • 对象不可以调用静态方法,因为和静态数据成员一样,静态类方法不属于某个对象,而属于整个类
  • 静态类方法当然也不能使用this指针,理由同第二条。由于静态类方法不和任何对象关联,所以他只能用类的静态数据成员,不可以访问其他私有数据成员。

默认构造函数中使用空指针

当没有参数的默认构造函数创建一个空字符串时,可以直接给str赋空指针,以避免用new,但析构函数还是可以delete,因为可以对空指针delete

StringBad::StringBad()
{strLen = 0;str = 0;//空指针,也可写为str = nullptr; 或者new char[strLen + 1];std::strcpy(str, "");++numStrings;std::cout << numStrings << ": default object created!\n";
}

其中nullptr是C++11提供的关键字

或者像上面代码写的:

StringBad::StringBad()
{strLen = 0;new char[strLen + 1];std::strcpy(str, "");++numStrings;std::cout << numStrings << ": default object created!\n";
}

构造和析构的new和delete注意事项总结

在这里插入图片描述在这里插入图片描述

构造函数使用new

  • 一定要在析构函数delete掉对象的所有指针成员
  • 构造函数用new,析构就要用delete[];构造用new[], 析构就要用delete[]。不能不配对。
  相关解决方案