c++ - Set initial value of unknown type or overload operator for specific parameters type -
i'm still learning c++ , fiddling operator overload.
now, have produce output, while don't know kind of data type on input - it's specified in makefile , can either double, struct or enum.
code first:
#include <iostream> #define type complex //#define type symbol //#define type double using namespace std; struct complex { double re; double im }; enum symbol { a, b, c, d, e }; struct vector { type data[4]; //more in struct, it's irrelevant }; // operator * overloads complex , symbol here // output stream operator vector, symbol , complex // overloaded type operator * (vector a, vector b) { type output; int i; (i=0; i<4; i++) { output = a.data[i] * b.data[i]; } return output; // output garbage, because type output not // set (to 0) @ beginning } int main { type x; // ... x = somevectora * somevectorb; cout << x << endl; // ... return 0; } as type output value not set after initialisation, overload produce garbage @ output - helps when set it, thtere problem. setting initial values each type done in different way.
so complex it's
complex x; x.re = 0; x.im = 0; for symbol
symbol x; x = e; and double always.
the solution came overload operator specific type:
double operator * (vector a, vector b); // [1] symbol operator * (vector a, vector b); // [2] complex operator * (vector a, vector b); // [3] but compiler throws me errors, because overloaded [3], though complex type input, , after [1] can't 2.05 * 1.1 anymore due incompatible data type.
i thinking adding init() function struct complex , struct vector. won't work enum.
checking type doesn't work either, compiler still throws errors.
the question
way set various overload procedures different input parameters or @ least avoid returning strange outputs in type operator * (vector a, vector b)?
try invoking default constructor, e.g:
type output = type();
Comments
Post a Comment