Operator overloading in some extent, the creative process. With her help, programmers it is possible to make it easier for yourself to write code, and for other – improve readability. For example, when some action has to be repeated many times in the code, and just painfully constantly use the special functions – you can overload an operator for this.
Let's, in the code it is necessary to often combine strings (append a string to a string class element). It can be designed in different ways. But we will do so, to strings concatenation happened then, when we use the statement + :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Overload { private: char str[256]; public: // какой-то код ... } int main { char strіng_1[] = "Название нашего сайта: "; char strіng_2[] = "PureCodeCpp"; Overload Object; // объявление объекта Object + strіng_1; Object + strіng_2; return 0; } |
The result should be a change in cellstr. He will in itself both strings: “The name of our website PureCodeCpp”.
While we do not explicitly override statement +, the compiler will “swear”, so as we put no numbers, and the strings. But now we learn how to tell him, how to act, When we ask to perform non-standard action, using+.
Getting practice. Define in example 4 strings. Next, collect one anecdote, combining them in the correct order in one string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | #include <iostream> using namespace std; class Overload { private: char str[256]; //строка, которая вместит все строки public: Overload() // очистим строку от "мусора" { for (int i = 0; i < 256; i++) str[i] = '\0'; } void operator +(char*); //прототип метода класса где будет перегружен + void showStr(); }; void Overload::operator +(char *s) // то, что надо выполнить при нахождении в коде оператора + { strcat_s(str, s); // дописать строку s в строку str } void Overload::showStr() { cout << str << endl << endl; } int main() { setlocale(LC_ALL, "rus"); char *str1 = "С лучезарным Челси на макушке.\n"; char *str2 = "Вся в гирляндах нефтяная вышка\n"; char *str3 = "Ёлка олигарха, так уж вышло,\n"; char *str4 = "Вовсе не дешёвая игрушка –\n"; cout << "1. " << str1; cout << "2. " << str2; cout << "3. " << str3; cout << "4. " << str4 << endl; Overload Joke; // объявляем объект и дописываем в его элемент строки используя уже перегруженный + Joke + str3; Joke + str4; Joke + str2; Joke + str1; cout << "=================================================" << endl; cout << "Анекдот, после записи строк в правильном порядке: " << endl; cout << "=================================================" << endl << endl; Joke.showStr(); // Сразу отметим, что для чисел оператор + будет выполнять сложение, как и должен int num_a = 15; int num_b = 5; int num_c = 0; num_c = num_a + num_b; cout << "=================================================" << endl << endl; cout << "num_a = " << num_a << endl << "num_b = " << num_b << endl; cout << "num_c = " << num_a << " + " << num_b << " = " << num_c << endl << endl; return 0; } |
Let's not talk about the obvious – proceed to reception of the overload. In string 15 we see a prototype of a class methodOverload: void statement +(char*); This method will cause the statement to work + so, that we want (as we define below). To overload any statement you want to use the keywordstatement. In our case, method does not return the values sovoid, Further keywordstatement and the statement itself +. It adopts this method on a string pointer.
In strings 20 – 23 it is the definition of the method of statement overloading. (How to define a class method is described in the article Classes in C ++) In him, using functionstrcat_s(str, s); write string s end of the stringstr (class element). It works so – as soon as the code meets the statement + which will be located behind the string – method is called statement overloading and this string will be transferred to it at the sign.
In the main function we defined in random order 4 strings. Display them on the screen (strings 39 – 42). Below, in string 44, declared objectJoke. At the time of its creation, the class constructor, cleanse class elementstr from “garbage” and it will be ready to record strings. Just follow these simple steps (strings 46 – 49) – using overloaded + write all strings into one (str) in the right order.
Result:
Everything turned out. And, as seen in the result, for numeric data statement + load correctly. Therefore you can calmly apply it for arithmetic operations in code – the compiler you “understand”. Another point – overload statement acts only within the class, for which it is defined. If we define another class (Overload2 for example) but not overwhelm him for the statement, the attempt to use + to write a string somewhere will result in an error.
There are a number of exceptions in c++ – not all statements can be overloaded. Here is a list:
And a little theory:
– overload statements can not change the priority and order of operations;
– there is no possibility, using overload, create new symbols for operations;
– binary statements cannot be used to override the unary operation, and vice versa – unary not override binary operation.
Statement overloading, of course, “thing” interesting. Just do not get carried away. Use it only when absolutely necessary – if it will really bring more convenience, saving you time and positively affect the code readability. Try to overload statements so, it to be as close as possible to their logical value. That is, it is not necessary to fold strings, statement overloading –, for example. It is more logical to use +.
I note, that many programmers do not like statement overloading, as some overly fond of it, and it becomes difficult to read the code. So carefully weigh the pros and cons, when deciding on overloading statements.
In the future I plan to write another article on overloading statements, where the examples I want to show how to overload ++ increment, — decrement, == equality, = assignmentnew and delete.
Additionally, watch the video on:
>> For example, when some action has to be repeated many times in the code, and just painfully permanent use for this special function - can overload statement for this.
In general, it is true, but overloading – It is a chic way to shoot yourself in the foot (and even shoot anything comrade). It is a dangerous thing. It can either increase the readability of the code, and all the spoil.
At Myers were the rules on this subject (if they do not comply with – Hell make you maintain your code all 7 circles). For example:
– assignment operator should return a reference to * this;
– in the assignment statement to check self-assignment;
– there tselyyel about overloading the new and delete, but IMHO 99% mortals simply do not need to touch these statements;
– declare function, non-members, When type conversion must be applied to all parameters.
Well, a number of other rules (a few books).
I suggest to pay attention to the last rule in the list. You have described the statement, who work for
Joke + str1;
But it is not going to work for
str1 + Joke;
But it would be nice if the statement would work in both directions. It's enough to make it not a member of the class (normal function of). It's not difficult? )
Visual Studio 2017 an error on : char *str1 = “С лучезарным Челси на макушке.\n”;
Error C2440 Initialization: can not be converted “const char [32]” in “char *”
– that where it is necessary to set up?
And in some lesson error: Error C3863 array type “bool [& n = 'function' +]” It is assignable on line bool a[n = atoi(argv[1]) + 1];
And in QT it compiles fine (although the syntax error highlighting)
I walked around like a: char *str1 = (char*)”С лучезарным Челси на макушке.\n”;
And further, Is not it enough to cleanse the point
char str[256] = {}; //string, who, instead of all rows