Übung richtig gelöst?
-
Hallo,
wie der Titel schon vielleicht erahnen lässt wollte ich mal Fragen ob sich jemand meine Lösungen bzw. Antworten zu den Übungsaufgaben des Primar 5 nachschauen kann.
Ich hab bei der letzte Antwort versucht mich möglichst Fachlich auszudrücken was mir glaub ich eher weniger gelungen ist. Was kann ich da besser machen bzw. welche Begriffe sind falsch gewählt oder welche fehlen?
Aufgabe 1:Assuming i is an int and d is a double write the expression i *= d so that it does integral, rather than floating-point, multiplication.Antwort 1:
i *= static_cast<int>(d); Aufgabe 2: Rewrite each of the following old-style casts to use a named cast: int i; double d; const string *ps; char *pc; void *pv; (a) pv = (void*)ps; (b) i = int(*pc); (c) pv = &d; (d) pc = (char*) pv;Antwort 2:
(a) pv = const_cast<void*>(ps); (b) i = reinterpret_cast<int>(pc); (c) pv = static_cast<void*>(&d); //oder so ? &static_cast<void*>(d); (d) pc = reinterpret_cast<char*>(pv);Aufgabe 3:
Explain the following expression: double slope = static_cast<double>(j/i);Anwort 3:
Falls j und i von unterschiedlichen Typen sind werden diese automatisch konvertiert. Nun wird Quotient wert errechnet. Anschließend wird das Ergebnis auf den Typ double explizit konvertiert und die Variable slope wird damit initialisiert.
-
^
-
2 b) sollte sein i = static_cast<int>(*pc), hier wird nur ein char in ein int konvertiert.
2 d) sollte sein pc = static_cast<char*>(pv), hier wird von void* konvertiert daher reicht ein static_cast. Ein reinterpret_cast wäre an dieser Stelle allerdings nicht falsch, nur eben "unschön".
Bei 2c) ist die erste Variante richtig.