#include <iostream>
#include <cstring>
using namespace std;
/*
g++ prog.cc -Wall -Wextra -std=gnu++17
*/
class Message {
public:
Message() = default;
Message(const char* text) {
m_length = strlen(text);
m_text = new char[m_length];
strcpy(m_text, text);
}
Message(const Message&) = delete;
Message& operator=(const Message&) = delete;
Message(Message&&rsh) {
m_text = rsh.m_text;
m_length = rsh.m_length;
rsh.m_text = nullptr;
rsh.m_length = 0;
}
Message& operator=(Message&&rsh) {
if( this == &rsh)
return *this;
m_text = rsh.m_text;
m_length = rsh.m_length;
rsh.m_text = nullptr;
rsh.m_length = 0;
return *this;
}
~Message(){
if(m_text!= nullptr) {
delete [] m_text;
}
}
friend Message operator+(const Message& lsh, const Message& rsh) {
Message result;
result.m_length = lsh.m_length + rsh.m_length;
result.m_text = new char[result.m_length];
strcpy(result.m_text, lsh.m_text);
strcpy(result.m_text + lsh.m_length, rsh.m_text);
return result;
}
void Print() const {
cout<<"Text: "<<m_text<<"; length: "<<m_length<<endl;
}
private:
char * m_text { nullptr };
int m_length { 0 };
};
int main()
{
Message lsh("hello "), rsh("world!");
(lsh+rsh).Print();
(Message("another one") + Message(" and another one!")).Print();
return 0;
}
Comments
Leave a comment