#include <iostream>
class Mystr{
private:
int length;
char *text;
public:
Mystr();
Mystr(const char*);
Mystr(const Mystr &obj);
Mystr(int);
~Mystr();
void print();
int count(const char);
int len(){
return length;
}
Mystr operator+(const Mystr &obj);
Mystr operator=(const Mystr &obj);
};
Mystr::Mystr(const char* str){
length = 0;
while (str[length] != '\0'){
length++;
}
text = new char[length+1];
for (int i = 0;i <= length;i++){
text[i] = str[i];
}
std::cout << "char* constructor is triggered" << std::endl;
}
Mystr::Mystr(){
length = 0;
text = NULL;
}
Mystr::Mystr(const Mystr &obj){
length = obj.length;
text = new char[length+1];
for (int i = 0;i <= obj.length;i++){
text[i] = obj.text[i];
}
std::cout << text << ": "<< "copy constructor is triggered" << std::endl;
}
Mystr::~Mystr(){
std::cout << text << ": ";
delete[] text;
std::cout << "destructor is triggered\n";
}
Mystr::Mystr(int n){
if (n > 0){
length = n;
text = new char[n+1];
text[n] = '\0';
while (n--){
text[n] = '*';
}
}else{
length = 0;
text = NULL;
}
std::cout << "int constructor is triggered" << std::endl;
}
void Mystr::print(){
for (int i = 0;i < length;i++){
std::cout << text[i];
}
std::cout << std::endl;
}
int Mystr::count(const char c){
int res = 0;
for (int i = 0; i < length;i++){
if (text[i] == c) res++;
}
return res;
}
Mystr Mystr::operator+(const Mystr &obj){
Mystr res;
res.length = this->length + obj.length;
res.text = new char[res.length + 1];
for (int i = 0;i < this->length;i++){
res.text[i] = this->text[i];
}
for (int i = 0;i <= obj.length;i++){
res.text[this->length + i] = obj.text[i];
}
std::cout << "operator+ is triggered" << std::endl;
return res;
}
Mystr Mystr::operator=(const Mystr &obj){
if (this != &obj){
length = obj.length;
delete[] this->text;
text = new char[length+1];
for (int i = 0;i <= obj.length;i++){
this->text[i] = obj.text[i];
}
}
std::cout << "operator= is triggered" << std::endl;
return *this;
}
int main(){
Mystr *pstr = new Mystr("Hello");
Mystr test1 = *pstr;
Mystr test2 = test1 + " World";
Mystr test3 = test2 + 3.14;
*pstr = test1 = test1;
test1.print();
test2.print();
test3.print();
std::cout << test1.count('l') << " " << test2.len() << std::endl;
delete pstr;
return 0;
}