passed as a reference
Remember that one of the reasons you might pass a pointer to a function is that you want to allow that function to change the value of what you passed it. For example, here's a super simple function to increase the value of the first number by 3:void add3(int* xptr) { *xptr = *xptr + 3;}
This works, but can be a bit annoying since we have to use the * dereference operator everywhere in our function. Also, we must remember to add the operator address when calling this function, such as:int a = 10;add3(&a);add3(&a);// now a is equal to 16
Because pointers can be difficult and sometimes "dangerous" to use, C++ tries to avoid some of the situations in which we might need to use them. The answer in this case is to use a reference variable as a parameter to the add3 function, like this:void add3(int& x) { x = x + 3;}
Specifying a reference type is similar to specifying a pointer type, except instead of a *, you use an & with the type. This means that the x passed to the function is a reference to the variable on which the function is called. Changing x in the function when x is a reference variable also changes the original value!int a = 10;add3(a); // works now, no pointers needed!add3(a); // now a = 16
Pass by reference is also used in C++ to return multiple values from a function (by passing multiple arguments by reference) or to avoid copying something that is large or doesn't make sense to copy.Passing streams for reference
As you know, copying is not allowed for streams. Then,we can use streamobjects (bothour enemy
eFlow
) for reference.Compared to using Pass by Address, we can write the same code much easier using Pass by Reference.int readtime(istream&);...int readtime(istream& in){int h, m, s;char c;in >> h >> c >> m >> c >> s;return h*3600 + m* 60+;}
As you can see, the function reads the elapsed time from ourhh:mm:ss
Format.
With these definitions I can say
int k = read time (cin);
when I have to read from the keyboard for a while.monitoring: Bothcin
and everythingifstream
Objects can be passed by referenceFlow
.Therefore I can also say:
ifstream fin("data.txt");int m = readtime(fin); // pass fin to istream as a reference
... if I have to read in betweenfrom a file Daten.txt
with the same functionreading time
.It would be wonderful to have a functionreading time
that can happen to anyonecin
orfin
Read in the elapsed time as argumenthh:mm:ss
format and return in seconds.
operator overload
C++ allows the programmer to create new types that actually behave like the built-in types, which means that the usual operators like *, <, ++ work with the new types and I/O with << and >>, and short .Although this isn't a main topic for this course, I want to address it so you understand that we really can create new types in C++ if we want to. Also, I should note that this is why + and >> etc work with C++Fragment
objects. The string library implementers have defined all of these operators for their good string type.
simple program
Let's write a program that draws a course this way.- They start at (0,0).
- Then you can get into "movements". A move of (-2,4) means a move 2 units down and 4 units to the right of your current position.
- The user continuously enters moves until finally entering one.
q
exit.
First solution. my first solutionIt's a fairly simple program. The meat of the program is: | operator overload.While it may be simple, it would be nice to be able to write the function as ifpoint it out were an inline type, meaning I could add dotsp em sayingp + m . |
|
|
prototype and definition?
To do this, we need to be able to tell the compiler whatp + m
means forpoint it out
objectsp
em
. This is very easy once you understand the following:a+b
is exactly the same as the function callOperator+(a,b)
I'm C++.
So if you want to tell the compiler something+
means for twopoint it out
objects, you must define the functionoperator+(point a, point b)
--- This isoverloada+
operator forpoint it out
s. The prototype is clear:
point operator+(point a, point b);
...at least I hope it's clear that if we add two points we have to return one point. The function definition is... like any other function definition:point operator+(point a, point b){ point S; S.x = a.x + b.x; S.y = a.y + b.y; returns S ;}
Using the overloaded operator
So with that supplement, here it ismy second versionfrom the program. Well, the syntactic sugar might not be worth the trouble here, but you'll probably use thosepoint it out
struct over and over again, and you'll like that you can addpoint it out
s. Wouldn't it be good to stop themFocus
work like this:point midpoint(point a, point b){ return (a + b)/2.0;}
Overload other operators
"Operator overload" is the term used to define versions of C++ operators for the new frameworks we're defining. Generally if you have a printoutA PB
, where "Π" represents an operator, this corresponds to a function callOperatorΠ(A,B)
.So to subtract two points, we would definepoint operator (point A, point B);
... and compare two points with less than we definedoperator bool<(point A, point B);
...or multiplying a point (left) by a real number (right) we would definedot operator*(dot A, double w);
Scalars Division operator
Well, in addition to the definitionoperator +
for twopoint it out
Objects, what else do you need? Spring,(a + b)
is an object of typepoint it out
, and I divide it by an object of typeDouble
, so I have to adjustoperator/(period, double)
. What kind of object do you want to return here?PointOperator/(PointP, duple z){ PointQ; Q.x = P.x/z; Q.y = P.y / z; gib Q back;}
E/A und Overhead
Just to complete our examples, see how to overload << and >>.Operator istream&>>(istream &in, Punkt &A){ char c; return in >> c >> A.x >> c >> A.y >> c;}ostream& operator<<(ostream &out, point A){ return out << '(' << A.x << ',' << A.y < <')';}
The prototypes for these two should really make sense. For example, earlier we talked about howcin >> x
really rates back tocin
.However, this is new"Return by reference".
Normally, when a function returns an object X, the object returned in the calling function is a copy of that X. By using return by reference, we're saying, "No, I want the calling function to get itexactly the same item I returned, not a copy". Of course, this can only be done with something that doesn't go out of scope and dies at the end of the function call.To summarize all these overloaded functions, consider this example:dot.hedot.cpp.
practical problems
- Incrementing a military watch(You may preferthis solution.) This is a simple example of passing by reference that modifies your argument.
- Reading binary numbersHere's a simple example where we use pass-by-reference to avoid making a copy of an istream object.