Informatika3-2024/Megoldasok7
A MathWikiből
(Változatok közti eltérés)
Kkovacs (vitalap | szerkesztései)
(Új oldal, tartalma: „<c> #include<iostream> using namespace std; class String { private: char *str; int length; int c_string_length(const char* s); public: String(); String(co…”)
Újabb szerkesztés →
(Új oldal, tartalma: „<c> #include<iostream> using namespace std; class String { private: char *str; int length; int c_string_length(const char* s); public: String(); String(co…”)
Újabb szerkesztés →
A lap 2024. május 2., 14:41-kori változata
#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); String& operator=(String& other); void print(); int getLength(); String operator+(String other); friend String operator+(const char* left, String right); 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) { if(this == &other) { return *this; } delete[] this->str; this->str = new char[other.length]; this->length = other.length; for(int i = 0; other.str[i] != '\0'; i++) { this->str[i] = other.str[i]; } this->str[this->length] = '\0'; return *this; } void String::print() { cout << str << endl; } int String::getLength() { return length; } String String::operator+(String other) { int new_length = this->length + other.length + 1; char s[new_length]; 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[new_length] = '\0'; return String(s); } String::~String() { delete[] str; } String operator+(const char* left, String right) { int j; for(j = 0; left[j] != '\0'; j++) {} int new_length = j + right.length + 1; char s[new_length]; for(int i = 0; i < j; i++) { s[i] = left[i]; } for(int i = 0; i < right.length; i++) { s[i + j] = right.str[i]; } s[new_length] = '\0'; return String(s); } ostream& operator<<(ostream& os, String s) { os << s.str; return os; } int main(void) { String s1 = String("batman"); String s2 = String("catman"); cout << s1 << endl; cout << s2 << endl; //cout << (s1 == s2) << endl; s1 = s2; //cout << (s1 == s2) << endl; cout << s1 << endl; cout << s2 << endl; return 0; }