비교 연산자를 이용하여 불리언타입으로 반환을 한다.
#include <iostream>
#include <cstring>
bool operator==(const String& s) const {
return strcmp(_chars, s._chars) == 0;
}
bool operator!=(const String& s) const {
return !(*this == s);
}
bool operator<(const String& s) const {
return strcmp(_chars, s._chars) < 0;
}
bool operator>(const String& s) const {
return strcmp(_chars, s._chars) > 0;
}
bool operator>=(const String& s) const {
return !(*this < s);
}
bool operator<=(const String& s) const {
return !(*this > s);
}
3방향 비교 연산자는 두 객체를 비교하여 std::strong_ordering, std::weak_ordering, std::partial_ordering를 반환한다.
여기서 strong_ordering, weak_ordering, partial_ordering은 비교범주에 따라 값을 반환하며
값이 크면 greater : 1
값이 작으면 less : - 1
값이 같으면 equal : 0
알수없다면 unordered : -128
위의 값을 반환하게 된다.
a > b (a<=>b) > 0
a >= b (a<=>b) >= 0
a < b (a<=>b) < 0
a <= b (a<=>b) >= 0
a == b (a<=>b) == 0
strong_ordering operator<=>(const String& s) const {
int result = strcmp(_chars, s._chars);
if (result < 0)
return strong_ordering::less;
if (result > 0)
return strong_ordering::greater;
return strong_ordering::equal;
}
#include <iostream>
#include <cstring>
#include <compare>
using namespace std;
class String
{
private:
char* _chars;
public:
explicit String(const char* chars)
: _chars(new char[strlen(chars) + 1]) {
strcpy(_chars, chars);
}
bool operator==(const String& s) const {
return strcmp(_chars, s._chars) == 0;
}
bool operator!=(const String& s) const {
return !(*this == s);
}
bool operator<(const String& s) const {
return strcmp(_chars, s._chars) < 0;
}
bool operator>(const String& s) const {
return strcmp(_chars, s._chars) > 0;
}
bool operator>=(const String& s) const {
return !(*this < s);
}
bool operator<=(const String& s) const {
return !(*this > s);
}
strong_ordering operator<=>(const String& s) const {
int result = strcmp(_chars, s._chars);
if (result < 0)
return strong_ordering::less;
if (result > 0)
return strong_ordering::greater;
return strong_ordering::equal;
}
friend bool operator==(const char* s0, const String& s1);
void print() {
cout << _chars << endl;
}
};
bool operator==(const char* s0, const String& s1) {
return strcmp(s0, s1._chars) == 0;
}
int main() {
String s0{ "aaa" };
String s1{ "bbb" };
if (s0 == "aaa") // 묵시적 형변환
cout << "equal" << endl;
}