Which are the implications of return a value as constant, reference and constant reference in C++? -


I am learning C ++ and I'm still confused about it. What is the effect of continuing in C ++, referencing and returning a value as a continuous reference? For example:

  const int example one (); Integer & amp; ExampleTwo (); Const int & amp; ExampleThree ();  

On all your cases, it is down below:

< Strong> • Return to context : The function call can be used as the left hand of the assignment. Like operator overloading, if you have operator [] overload, you can say something like

  a [i] = 7;  

(When returning by reference, you need to make sure that the object returned by you is available after return: you should not return any reference to local or temporary) < / P>

Return as a continuous value : The assignment prevents the assignment from being used on the left side of the expression. Think overloaded operator + can write something like this:

  a + b = c; // It is not correct  

Return type operator allows to return by value as "some type" and at the same time prevents expression from being used on the left one Assignments.

  if (some function () == 2)  

  constite some functions ()  

then above (if) the typo will be caught by the compiler.

• Return as a continuous reference : This function call can not appear on the left hand of an assignment, and you can avoid making a copy (back by value) Want to Let's say that we have a class student and we want to provide an addresser ID () to get the student's ID:

  class student {std :: string id_; Public: const std :: string & amp; ID () console; }; Const std :: string & amp; Students: ID () {Return ID_; }  

Consider the ID () accessor. To confirm this, it should be declared a consonant that the id () member will not modify the state of the object. Now, consider the return type. If return type was string & amp; So someone can write something like this:

  Students; S.id () = "new ID";  

That which is not what we want is what we want.

We could have been refunded from the price, but the returning cases in this context are more efficient. Return Type One Constant & amp; Additionally, the ID prevents it from being modified.


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -