设计CString,所有错误使用异常设计。
时间: 2023-06-16 13:07:04 浏览: 87
在++ 中,可以使用异常机制来处理运行时错误。可以在类中添加适当的异常处理语句,以便在出现错误时抛出异常。
下面是一个使用异常机制的 CString 类的示例:
```cpp
#include <iostream>
#include <cstring>
#include <stdexcept>
class CString
{
private:
char* m_str;
int m_len;
public:
CString(const char* str)
{
if (str == nullptr)
{
throw std::invalid_argument("Null pointer argument");
}
m_len = strlen(str);
m_str = new char[m_len + 1];
strncpy(m_str, str, m_len + 1);
}
CString(const CString& other)
{
m_len = other.m_len;
m_str = new char[m_len + 1];
strncpy(m_str, other.m_str, m_len + 1);
}
~CString()
{
delete[] m_str;
}
CString& operator=(const CString& other)
{
if (this != &other)
{
delete[] m_str;
m_len = other.m_len;
m_str = new char[m_len + 1];
strncpy(m_str, other.m_str, m_len + 1);
}
return *this;
}
char operator[](int index) const
{
if (index < 0 || index >= m_len)
{
throw std::out_of_range("Index out of range");
}
return m_str[index];
}
friend std::ostream& operator<<(std::ostream& os, const CString& str)
{
os << str.m_str;
return os;
}
};
int main()
{
try
{
CString str1("Hello");
std::cout << str1 << std::endl;
CString str2 = str1;
std::cout << str2 << std::endl;
char ch = str1[3];
std::cout << ch << std::endl;
CString str3(nullptr); // throws an exception
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
```
在这个示例中,CString 类的构造函数和索引运算符都检查了输入参数是否合法,并在不合法时抛出了异常。而在主函数中,使用了 try-catch 块来捕获异常并处理错误。这样可以使程序更加健壮和安全。