Skip to content

Instantly share code, notes, and snippets.

@HilarioNengareJr
Created January 19, 2022 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HilarioNengareJr/6458d073c0b6c1ebc0f77a931fb1e334 to your computer and use it in GitHub Desktop.
Save HilarioNengareJr/6458d073c0b6c1ebc0f77a931fb1e334 to your computer and use it in GitHub Desktop.
Overloading operators in C++ basic blueprint.
String & operator += (const String & other) {
int newlen = _len + other._len; // calc new length
char * newstr = new char[newlen + 1]; // alloc new buffer
strcpy(newstr, _s); // copy own contents
strcpy(newstr + _len, other._s); // append new contents
delete[] _s; // release orig memory
_s = newstr; // install new buffer
return *this;
}
String operator + (const String & s1,
const String & s2) {
String result(s1); // clone s1 using copy ctor
result += s2; // append s2
return result; // return new result
}
// + for different types
String operator + (const String & s1,
const char * s2) {
String result(s1); // clone s1 using copy ctor
result += String(s2); // append String converted s2
return result; // return new result
}
bool operator == (const String & s1,
const String & s2) {
return (strcmp(s1.data(), s2.data()) == 0);
}
bool operator != (const String & s1,
const String & s2) {
return (strcmp(s1.data(), s2.data()) != 0);
}
char & String::operator[](int i) {
// check for range
// non-const version allows string[n] to be used as lvalue
return _s[i];
}
const char & String::operator[](int i) const {
// check for range here
// const version allows access to const objects
return _s[i];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment