So i tried re-implementing my own string class using smart pointers just so I can practice integrating them into my daily use. Sadly, I've hit a wall, and I can't figure out why I'm unable to concatenate two "mystring" objects. Any suggestions? Also, if this type of program isn't the proper situation to use smart pointers in, I would also appreciate advice related to that as well.
#include <iostream>
#include <memory>
#include <cstring>
using namespace std;
class mystring {
public:
mystring() : word(make_unique<char[]>('\0')), len(0) {}
~mystring() { cout << "goodbye objects!";}
mystring(const char *message) : word(make_unique<char[]>(strlen(message) + 1)), len(strlen(message)) {
for (int i = 0; i < len; i++) word[i] = message[i];
}
mystring(const mystring &rhs) : word(make_unique<char[]>(rhs.len)), len(rhs.len + 1) {
for (int i = 0; i < len; i++) word[i] = rhs.word[i];
}
mystring &operator=(mystring &rhs) {
if (this != &rhs) {
char *temp = word.release();
delete[] temp;
word = make_unique<char[]>(rhs.len + 1);
len = rhs.len;
for (int i = 0; i < len; i++) word[i] = rhs.word[i];
}
return *this;
}
mystring &operator=(const char *rhs) {
char *temp = word.release();
delete[] temp;
word = make_unique<char[]>(strlen(rhs)+ 1);
len = strlen(rhs);
for (int i = 0; i < len; i++) word[i] = rhs[i];
return *this;
}
friend mystring operator+(const mystring& lhs, const mystring& rhs) {
mystring Result;
int lhsLength = lhs.len, rhsLength = rhs.len;
Result.word = make_unique<char[]>(lhsLength + rhsLength + 1);
Result.len = lhsLength + rhsLength;
for (int i = 0; i < lhsLength; i++) Result.word[i] = lhs.word[i];
for (int i = lhsLength; i < lhsLength + rhsLength; i++) Result.word[i] = rhs.word[i];
return Result;
}
friend ostream &operator<<(ostream &os, mystring &message) {
for (int i = 0; i < message.len; i++) os << message.word[i];
return os;
}
private:
int len;
unique_ptr<char[]> word;
};
int main()
{
mystring word1 = "Darien", word2 = "Miller", word3;
cout << word1 + word2;//error message: no binary '<' found
word3 = word1 + word2;//error message: no binary '=' found
cout << word3;
return 0;
}
Change the parameter message's type of operator<< from mystring & (reference to non-const) to const mystring & (reference to const):
friend ostream &operator<<(ostream &os, const mystring &message) {
for (int i = 0; i < message.len; i++) os << message.word[i];
return os;
}
operator+ returns by value, so what it returns is a temporary, which can't be bound to reference to non-const.
Note that you should do this not only for solving this issue; message shouldn't be passed by reference to non-const because the argument is not supposed to be modified inside operator<<.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With