// Overloading the operator + . #include #include #include const int max_len = 255; class string { public: void assign(const char* st) { strcpy(s, st); len = strlen(st); } int length() { return len; } void print() { cout << s << "\nLength: " << len << endl; } friend string operator+(const string& a, const string& b); private: char s[max_len]; int len; }; string operator+(const string& a, const string& b) // overload + { string tmp; tmp.assign(a.s); tmp.len = a.len + b.len; if (tmp.len < max_len) strcat(tmp.s, b.s); else { cerr << "Max length exceeded in concatenation - bye!\n"; exit(1); } return tmp; } void print(const char* c) // fct def for file scope print() { cout << c << "\nLength: " << strlen(c) << "\n"; } int main() { string one, two, both; char three[40] = {"My name is Charles Babbage."}; one.assign("My name is Alan Turing."); two.assign(three); print(three); // file scope print() called // Print shorter of one and two. if (one.length() <= two.length()) one.print(); // member fct print() called else two.print(); both = one + two; // plus overloaded to be concatenate both.print(); return 0; }