Created
January 11, 2020 00:11
-
-
Save misterpoloy/fcbd6f937063e003b17c2ab532987b37 to your computer and use it in GitHub Desktop.
Naiv String Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.youtube.com/watch?v=ijIxcB9qjaU&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=32 | |
#include <iostream> | |
class String { | |
private: | |
char* m_Buffer; | |
unsigned int m_Size; | |
public: | |
String(const char* string) { | |
m_Size = strlen(string); | |
m_Buffer = new char(m_Size + 1); | |
memcpy(m_Buffer, string, m_Size); | |
// null termination operator | |
m_Buffer[m_Size] = 0; | |
} | |
// Like unique pointers String(const String& other) = delete; | |
String(const String& other) | |
: m_Size(other.m_Size) { | |
m_Buffer = new char(m_Size + 1); | |
memcpy(m_Buffer, other.m_Buffer, m_Size); | |
// m_Buffer[m_Size] = 0; The original already have the null termination | |
} | |
~String() { | |
delete [] m_Buffer; | |
} | |
char& operator[](unsigned int index) { | |
return m_Buffer[index]; | |
} | |
friend std::ostream& operator <<(std::ostream& stream, const String& string); | |
}; | |
std::ostream& operator <<(std::ostream& stream, const String& string) { | |
stream << string.m_Buffer; | |
return stream; | |
} | |
int main() { | |
String string = "cherno"; | |
String string2 = string; | |
string2[2] = 'a'; | |
std::cout << string << std::endl; | |
std::cout << string2 << std::endl; | |
std::cin.get(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment