gpt4 book ai didi

c++ - 为什么这个断言失败了?

转载 作者:行者123 更新时间:2023-11-28 06:01:10 26 4
gpt4 key购买 nike

main.cpp 中的assert 失败了,我不明白为什么。这是string.hpp

class String
{
private:
int len;
char* str;
public:
String(char const* s); // C-string constructor
~String() {delete str;}; // destructor
char* const getString(); //get string for printing
};

inline bool operator==(String lhs, String rhs)
{
return std::strcmp(lhs.getString(),rhs.getString());
}

// Define operator!= in terms of ==
inline bool operator!=(String const& lhs, String const& rhs)
{
return !(lhs == rhs);
}

这里是string.cpp

String::String(char const* s)   // C-string constructor
{
len = std::strlen(s);
str = new char[len+1];
std::strcpy(str,s);

}

char* const String::getString()
{
return str;
}

这里是 main.cpp

#include <cassert>
int main()
{
String c = "c";
String d = "d";

assert(c == c);
assert(c != d);
}

我试图只包含必要的代码。我遗漏了很多明显的包括。 assert(c == d) 失败了,我不明白为什么。 == 的运算符重载应该返回 true 结果。

最佳答案

如果字符串相等,

std::strcmp 返回 0。因此,您的 operator== 将为相等的字符串返回 false,否则返回 true

例如,您可以切换 ==!= 的实现,

关于c++ - 为什么这个断言失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com