Multipliziert Komplex mit konstantem in C ++
-
27-09-2019 - |
Frage
Der folgende Code nicht compiliert
#include <iostream>
#include <cmath>
#include <complex>
using namespace std;
int main(void)
{
const double b=3;
complex <double> i(0, 1), comp;
comp = b*i;
comp = 3*i;
return 0;
}
mit Fehler: keine Übereinstimmung für ‚operator *‘ in ‚3 * i‘ Was stimmt hier nicht, warum kann ich nicht mehrfach mit sofortigen Konstanten? b * i funktioniert.
Lösung
In der ersten Zeile:
comp = b*i;
Die Compiler Anrufe:
template<class T> complex<T> operator*(const T& val, const complex<T>& rhs);
, die als instanziert wird:
template<> complex<double> operator*(const double& val, const complex<double>& rhs);
Im zweiten Fall gibt es keine entsprechende Vorlage int
, so die Instancing fehlschlägt:
comp = 3.0 * i; // no operator*(int, complex<double>)
Andere Tipps
Siehe http://www.cplusplus.com/reference/std / Areal / Areal / Betreiber / für einen Überblick über die komplexen Operatoren.
Sie werden feststellen, dass der Operator * eine Vorlage und die Template-Parameter der komplexen Klasse verwenden, um diesen Code zu generieren. Die Zahlenliteral Sie Operator aufzurufen verwenden * ist vom Typ int. Verwenden comp = 3. * i;
die std::complex
Klasse ist ein wenig dumm ... definieren diese automatische Aktionen zu ermöglichen:
// Trick to allow type promotion below
template <typename T>
struct identity_t { typedef T type; };
/// Make working with std::complex<> nubmers suck less... allow promotion.
#define COMPLEX_OPS(OP) \
template <typename _Tp> \
std::complex<_Tp> \
operator OP(std::complex<_Tp> lhs, const typename identity_t<_Tp>::type & rhs) \
{ \
return lhs OP rhs; \
} \
template <typename _Tp> \
std::complex<_Tp> \
operator OP(const typename identity_t<_Tp>::type & lhs, const std::complex<_Tp> & rhs) \
{ \
return lhs OP rhs; \
}
COMPLEX_OPS(+)
COMPLEX_OPS(-)
COMPLEX_OPS(*)
COMPLEX_OPS(/)
#undef COMPLEX_OPS