forloRn_
Legacy Member
Als je een variabele typecast dan wordt er een tijdelijke variabele aangemaakt, niet? Die tijdelijke variabele, is die constant (const)?
In mijn boek vind ik het volgende:
Dat klinkt logisch, maar ik slaag er niet in het volgende te compileren (bij wijze van test):
Reactie van de compiler:
De code slaat op niets, dat weet ik, ik wilde gewoon eventjes een tijdelijke variabele maken.
Waarom compileert dit niet?
In mijn boek vind ik het volgende:
Actual arguments must be type-compatible with the formal arguments, without the use of a typecast. This is required because a typecast generates a temporary variable and that temporary variable would become the actual argument. Then changes to the formal parameter in the invoked function would change the temporary variable (instead of the original), leading to hard-to-find bugs.
Dat klinkt logisch, maar ik slaag er niet in het volgende te compileren (bij wijze van test):
Code:
#include <iostream>
using namespace std;
class Persoon {
public:
Persoon(const string &n): naam(n) {
}
string naam;
};
class Student: public Persoon {
public:
Student(const string &n): Persoon(n) {
}
};
void veranderNaam(Persoon &p, const string &n) {
p.naam = n;
}
int main() {
Student s("Fred");
veranderNaam((Persoon)s, "Mark");
cout << "Naam: " << s.naam << endl;
return EXIT_SUCCESS;
}
Reactie van de compiler:
../main.cpp: In function `int main()':
../main.cpp:24: error: invalid initialization of non-const reference of type 'Persoon&' from a temporary of type 'Persoon'
../main.cpp:18: error: in passing argument 1 of `void veranderNaam(Persoon&, const std:tring&)'
mingw32-make.exe: *** [main.o] Error 1
De code slaat op niets, dat weet ik, ik wilde gewoon eventjes een tijdelijke variabele maken.
Waarom compileert dit niet?
tring&)'
.