0

The assert in main.cpp is failing, and I don't understand why. Here is 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);
}

and here is 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;
}

and here is main.cpp

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

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

I tried to include only the essential code. I left out a lot of the obvious includes. The assert(c == d) is failing and I don't understand why. The operator overload of == should have returned a true result.

2 Answers2

1

std::strcmp returns 0 if the strings are equal. So your operator== will return false for equal strings and true else.

You could, for instance, switch the implementations of == and != around,

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
0

strcmp returns 0 when its arguments have equal contents.

So add a comparison with 0 to your operator==:

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

Also, since you probably don't want to copy the arguments each time you call operator==, I'd recommend passing them by reference.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157