I'm trying to implement custom String
class and I'm failing at console output, I have the following code:
class MyString {
public:
MyString() {
_length = 0;
_str = new char[0];
}
MyString(const char* c_str) {
_length = 0;
if (c_str) {
while (c_str[_length] != '\0') {
++_length;
}
}
_str = new char[_length];
for (size_t i = 0; i < _length; ++i) {
_str[i] = c_str[i];
}
}
~MyString() {
delete[] _str;
}
size_t length() const {
return _length;
}
friend ostream& operator<<(ostream& os, const MyString& str) {
if (str._length > 0) {
for (size_t i = 0; i < str._length; ++i) os << str._str[i];
} else os << "";
return os;
}
private:
char* _str;
size_t _length;
};
It seems to work okay, but when I use vector
of such objects I have strange symbols in my output, look (idk how it will be shown at stack, sorry):
vector<MyString> my_strings;
my_strings.push_back(MyString("The longest string in the world"));
cout << my_strings.front() << endl;
Output: ▄└ ▄est string in the world
But when I'm just:
cout << MyString("The longest string in the world") << endl;
Output: The longest string in the world
What am I doing wrong?