Informatika3-2024/Megoldasok7
A MathWikiből
#include<iostream> using namespace std; class String { private: char *str; int length; int c_string_length(const char* s); public: String(); String(const char* s); String(const String& other); void print(); String operator+(String other); bool operator==(String other); String& operator=(String& other); friend ostream& operator<<(ostream& os, String s); ~String(); }; int String::c_string_length(const char* s) { int i; for(i = 0; s[i] != '\0'; i++) {} return i; } String::String() { str = new char[1]; str[0] = '\0'; length = 0; } String::String(const char* s) { length = c_string_length(s); str = new char[length + 1]; for(int i = 0; s[i] != '\0'; i++) { str[i] = s[i]; } str[length] = '\0'; } String::String(const String& other) { this->length = other.length; str = new char[this->length + 1]; for(int i = 0; other.str[i] != '\0'; i++) { this->str[i] = other.str[i]; } this->str[this->length] = '\0'; } String String::operator+(String other) { char* s = new char[this->length + other.length + 1]; for(int i = 0; i < this->length; i++) { s[i] = this->str[i]; } for(int i = 0; i < other.length; i++) { s[i + this->length] = other.str[i]; } s[this->length + other.length] = '\0'; String ret = String(s); delete[] s; return ret; } void String::print() { cout << str << endl; } bool String::operator==(String other) { /* if(this->length != other.length) { return false; } */ for(int i = 0; i < this->length + 1; i++) { if (this->str[i] != other.str[i]) { return false; } } return true; } String& String::operator=(String& other) { if(this == &other) { return *this; } delete[] this->str; this->str = new char[other.length + 1]; for(int i = 0; i < other.length; i++) { this->str[i] = other.str[i]; } this->str[other.length] = '\0'; this->length = other.length; return *this; } String::~String() { delete[] str; } ostream& operator<<(ostream& os, String s) { cout << s.str; return os; } String& String::operator=(const char* str) { } int main(void) { String a; String b("batman"); String c(b); String d("catman"); String e = b + d; //String e = b.operator+(d); cout << e << endl; //operator<<(operator<<(cout, e), endl); cout << (a == b) << endl; a = b; a = a; cout << (a == b) << endl; return 0; }