Reputation: 61
I'm studing structures, in the fallowing code my teacher created a structure of the complex numbers (numbers that are formed by two parts: a real one and an imaginary one).
#include <iostream>
#include <cmath>
#ifndef COMPLEX_DATA_H
#define COMPLEX_DATA_H
struct complex_data
{
double re = 0; // real part
double im = 0; // immaginary part
};
#endif
int main()
{
std::cout << "Insert two complex numbers (re, im): ";
complex_data z1, z2;
std::cin >> z1.re >> z1.im;
std::cin >> z2.re >> z2.im;
... // the code continues
}
I'd like to ask two questions:
Leaving z1 and z2 uninitialized will cause any trouble considering they're inside a function and their default inizialitation is undefined?
How can we write the actual form of a variable that is a complex number?
In reality is something like this c = 3 + 2i.
But if we write it, the computer will sum it because it don't know the difference between real numbers and imaginary ones. So we'll be forced to use a string, but in this case it'll become a sequence of charcaters! Any idea?
Using Ubuntu 14.04, g++ 4.9.2.
Upvotes: 1
Views: 577
Reputation: 218278
Since C++11, you have User defined literal (and since C++14 you have the standard literal operator ""i for the pure imaginary number of std::complex<double>
).
You may write your own operator ""_i
for your custom struct complex_data
and also operator +
to have what you expect, something like:
constexpr complex_data operator"" _i(unsigned long long d)
{ return complex_data{ 0.0, static_cast<double>(d) }; }
Upvotes: 1
Reputation: 1458
Q1- Constructors are meant to intialize the member variables use them. Q2- Actual Form can be written using strings its just matter of displaying. c = 3 + 2i. Compiler really dont know this, you can overload + operarator. if you define + operator addition will be performed. (whatever code is written in that function e.g real+= a.real;)
Upvotes: 0