【发布时间】:2019-09-29 07:19:54
【问题描述】:
我得到一个空白输出。我是新手,为此苦苦挣扎了一段时间。
我得到了编译器的 0 个错误。
还有什么可以改进的?
如何在不必使用static_cast 的情况下将const char* 的长度作为int 而不是size_t。
#include <iostream>
#include <cassert>
class String
{
private:
char* Str_Buffer{};
int Str_Size{};
public:
String(const char* string = " ")
: Str_Size{ static_cast<int>(strlen(string)) }
{
Str_Buffer = new char[Str_Size];
}
String& operator=(const String& string)
{
if (this == &string)
return *this;
delete[] Str_Buffer;
Str_Size = string.Str_Size;
if (string.Str_Buffer)
{
Str_Buffer = new char[Str_Size];
for (int index{ 0 }; index < Str_Size; ++index)
Str_Buffer[index] = string.Str_Buffer[index];
}
return *this;
}
char& operator[](const int index)
{
assert(index >= 0);
assert(index < Str_Size);
return Str_Buffer[index];
}
friend std::ostream& operator<<(std::ostream& out, const String& string)
{
out << string.Str_Buffer;
return out;
}
~String()
{
delete[] Str_Buffer;
}
};
int main()
{
String word("Hello world!");
std::cout << word;
return 0;
}
【问题讨论】:
-
你的代码doesn't compile。
-
对于
strlen(),您必须包含<cstring>,它位于命名空间std中。
标签: c++ string class raii resource-management