Questions and codes
Read the textbook example 10.1. This example implements a complex number class, but in the ointment, the real and imaginary parts of the plural class are fixed only as double types. The complex can be designed by the technical means of the template class to make the type of the real and imaginary parts the actual type specified when the object is defined.
(1) A class member function is required to be defined outside the class.
(2) On this basis, the subtraction, multiplication and division are realized again.
/* Copyright (c) 2015, Yantai University School of Computer * All rights reserved. * File name: Test.cpp * Author: Simbin * Completion Date: April 12, 2015 * Version number: v1.0 */#include <iostream>using namespace std;template< Class Numtype>class Complex{public:complex () {} Complex (Numtype xx,numtype yy): X (xx), Y (yy) {} Complex Complex_a DD (Complex &a); Complex complex_subtract (Complex &a); Complex complex_multiply (Complex &a); Complex Complex_divid (Complex &a); Complex display ();p rivate:numtype x; Numtype y;}; Template<class numtype>complex<numtype> Complex<numtype>::complex_add (Complex<numtype> &a) {Complex T; t.x=x+a.x; T.Y=Y+A.Y; return t;} Template<class numtype>complex<numtype> Complex<numtype>::complex_subtract (Complex<numtype > &a) {Complex T; t.x=x-a.x; T.Y=Y-A.Y; return t;} Template<class numtype>complex<numtype> complex<numtype>::complex_multiply (Complex<numtype > &a) {CompLex T; t.x=x*a.x; T.Y=Y*A.Y; return t;} Template<class numtype>complex<numtype> Complex<numtype>::complex_divid (Complex<numtype> &a) {Complex T; t.x=x/a.x; T.Y=Y/A.Y; return t;} Template<class numtype>complex<numtype> complex<numtype>::d isplay () {cout<< "(" <<x << "," <<y<< ")" <<ENDL; int main () {complex<int> C1 (3,4), C2 (5,-10), C3; The real and imaginary parts are of type int 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 part and the imaginary part are double type c6=c4.complex_add (C5); cout<< "c4+c5="; C6.display (); The following tests subtract, multiply and divide c3=c1.complex_subtract (C2); cout<< "c1-c2="; C3.display (); C3=c1.complex_multiply (C2); cout<< "c1*c2="; C3.display (); C3=c1.complex_divid (C2); cout<< "c1/c2="; C3.display (); return 0;}
Operation Result:
Six weeks on-machine practice Project 6--Copy template class (1)