Week 6 (class template) and week 6 class template
/*
* Copyright (c) 2015, computer College, Yantai University
* All rights reserved.
* File name: Week 6 (class template)
* Author: Wang Zhong
* Completion date: 2015.4.14
* Version: v1.0
*
* Problem description: you can design Complex using the template technology to set the real and virtual types to the actual types specified when defining objects.
(1) class member functions must be defined outside the class.
(2) On this basis, subtraction, multiplication, and division are implemented.
* Input description:
* Program output:
# Include <iostream> using namespace std; template <class numtype> class Complex {public: Complex () {real = 0; imag = 0;} Complex (numtype r, numtype I) {real = r; imag = I;} Complex complex_add (Complex & c2); Complex complex_str (Complex & c2); Complex complex_mul (Complex & c2 ); complex complex_div (Complex & c2); void display (); private: numtype real, imag;}; template <class numtype> Complex <numtype> :: complex_add (Complex & c2) {Complex c; c. real = real + c2.real; c. imag = imag + c2.imag; return c;} template <class numtype> Complex <numtype >:: complex_str (Complex & c2) {Complex c; c. real = real-c2.real; c. imag = imag-c2.imag; return c;} template <class numtype> Complex <numtype>: complex_mul (Complex & c2) {Complex c; c. real = real * c2.real-imag * c2.imag; c. imag = imag * c2.real + real * c2.imag; return c;} template <class numtype> Complex <numtype>: complex_div (Complex & c2) {Complex c; numtype a; a = c2.real * c2.real + c2.imag * c2.imag; c. real = (real * c2.real + imag * c2.imag)/a; c. imag = (imag * c2.real-real * c2.imag)/a; return c;} template <class numtype> void Complex <numtype>: display () {cout <"(" <real <"," <imag <"I)" <endl;} int main () {Complex <int> c1 (3, 4), c2 (5,-10), c3; // the real and virtual parts are int type c3 = c1.complex _ add (c2 ); cout <"c1 + c2 ="; c3.display (); Complex <double> c4 (3.1, 4.4), c5 (5.34,-10.21), c6; // The real and virtual parts are double type c6 = c4.complex _ add (c5); cout <"c4 + c5 ="; c6.display (); // The following test subtraction, multiplication, and Division c3 = c1.complex _ str (c2); cout <"c1-c2 ="; c3.display (); c3 = c1.complex _ mul (c2 ); cout <"c1 * c2 ="; c3.display (); c3 = c1.complex _ div (c2); cout <"c1/c2 ="; c3.display (); return 0 ;}
When I imitate the multiplication and division and run the result, I found that multiplication and division of the plural are not the same thing. I am depressed and tangled.