// Compile with: // g++ -Wall -o komplex-class komplex-class.cc #include struct komplex { double re; double im; // Default (empty) constructor. komplex() { re = 0; im = 0; } // Constructor that creates a komplex out of a double. komplex(double r) { re = r; im = 0; } // Constructor that creates a komplex out of two doubles. komplex(double r, double i) { re = r; im = i; } // Implementation of "this += b". komplex & operator += (const komplex & b) { re += b.re; im += b.im; return *this; } // Implementation of "this -= b". komplex & operator -= (const komplex & b) { re -= b.re; im -= b.im; return *this; } // Prints a komplex to cout. void print() { std::cout << "komplex[" << re << "," << im << "]"; } }; // Implementation of "a+b". komplex operator + (const komplex & a, const komplex & b) { return komplex(a.re+b.re, a.im+b.im); } // Implementation of "a-b". komplex operator - (const komplex & a, const komplex & b) { return komplex(a.re-b.re, a.im-b.im); } int main() { komplex a; komplex b = 1; komplex c(2,4); komplex d = c; komplex e = b+c; std::cout << "a = "; a.print(); std::cout << std::endl; std::cout << "b = 1 = "; b.print(); std::cout << std::endl; std::cout << "c = (2,4) = "; c.print(); std::cout << std::endl; std::cout << "d = c = "; d.print(); std::cout << std::endl; std::cout << "e = b+c = "; e.print(); std::cout << std::endl; b += e; std::cout << "b += e = "; b.print(); std::cout << std::endl; return 0; }