Gast
#1092972
Hallo
kann mir mal jemand den Unterschied zwischen einer expliziten und
einer impliziten Typwandlung erklähren? Das Programm sieht so aus.
Danke
/*-------------------+----------------------------+--------------------+
| Ohm-Hochschule | | convers2.cpp |
| Nuernberg | Programmieren in C++ |--------------------|
| Peter Jesorsky | | 02.07.2007 |
+--------------------+----------------------------+-------------------*/
/*
Einsatz einer Typumwandlungs-Funktion
*/
#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
public:
Complex(double r = 0, double i = 0); // Konstruktor
operator double() const; // Umwandlungsfunktion
private:
double re, im;
};
Complex::Complex(double r /* = 0 */, double i /* = 0 */)
{
re = r;
im = i;
cout << "Konstruktor: (" << re << " , " << im << ")\n";
}
Complex::operator double() const // Umwandlungsfunktion
{
cout << "Umwandlung Complex = (" << re << " , " << im
<< ") -> double = " << sqrt(re * re + im * im) << endl;
return sqrt(re * re + im * im);
}
int main(void)
{
Complex x(3, 4); // Konstruktor-Aufruf zur Erzeugung von x
double dbl;
dbl = x; // implizite Typumwandlung Complex -> double
// mit Umwandlungsfunktion
dbl = (double)x; // explizite Typumwandlung
dbl = double(x); // das gleiche mit neuer Syntax!
cout << dbl << '\n';
return 0;
}
/* Ausgabe:
------------------------------------------------------------------------
Konstruktor: (3 , 4)
Umwandlung Complex = (3 , 4) -> double = 5
Umwandlung Complex = (3 , 4) -> double = 5
Umwandlung Complex = (3 , 4) -> double = 5
5
----------------------------------------------------------------------*/