#include <iostream>
struct String
{
public:
String();
String(const char *str);
String(const String& str);
void print();
~String();
String& operator=(const String& other);
String operator+(const String& other);
private:
char *str;
int lenght;
};
String::String()
{
this->str = nullptr;
lenght = 0;
}
String::String(const char *str)
{
lenght = strlen(str);
this->str = new char[lenght + 1];
for(int i = 0; i < lenght; i++)
{
this->str[i] = str[i];
}
this->str[lenght] = '\0';
}
String::String(const String& other)
{
lenght = other.lenght;
this->str = new char[lenght + 1];
for (int i = 0; i < lenght; i++)
{
this->str[i] = other.str[i];
}
this->str[other.lenght] = '\0';
}
void String::print()
{
std::cout << str;
}
String::~String()
{
delete[] this->str;
this->str = nullptr;
}
String& String::operator=(const String& other)
{
if (this->str != nullptr)
{
delete[] str;
str = nullptr;
}
lenght = other.lenght;
this->str = new char[lenght + 1];
for (int i = 0; i < lenght; i++)
{
this->str[i] = other.str[i];
}
this->str[other.lenght] = '\0';
return *this;
}
String String::operator+(const String& other)
{
String NewStr;
NewStr.lenght = this->lenght + other.lenght;
NewStr.str = new char[NewStr.lenght + 1];
int i = 0;
for (;i < this->lenght; i++)
{
NewStr.str[i] = this->str[i];
}
for (int j = 0; j < other.lenght; j++, i++)
{
NewStr.str[i] = other.str[j];//предупреждение в этой строке
}
NewStr.str[NewStr.lenght] = '\0';
return NewStr;
}
int main()
{
String a("Hello");
String b("lello");
String c;
c = a + b;
c.print();
}
更换时
NewStr.lenght = this->lenght + other.lenght;
NewStr.str = new char[NewStr.lenght + 1];
在
NewStr.lenght = this->lenght + other.lenght;
NewStr.str = new char[this->lenght + other.lenght + 1];
警告消失
人工代码分析是一个非常“创造性”的过程。人们可以看到与和究竟
NewStr.lenght是如何联系在一起的。但将所有可能的分析模式都纳入算法中是不现实的。具体来说,这里的代码分析器没有看到/计算这种依赖关系。但是他的假设虽然是错误的,但是从程序员在代码中表达思想的一致性的角度来看,还是好的。看看你的代码,你可以说第二个循环是第一个循环的延续,但是主体略有改变。但算法没有读取它。这些变化不仅影响了身体,也影响了柜台。我们在两个循环中都进行迭代,它的计数器是。现在对于分析仪来说,这是两个不相关的循环:第一个循环带有和计数器,第二个循环带有和计数器和。代替this->lenghtother.lenghtNewStr.striNewStrthisiNewStrotherij在
现在两个循环都通过条件
i、增量i和迭代连接i起来NewStr.str。这更有意义。最有趣的是警告消失了。