it-place.net > Уроци > C-Cplusplus
Не сте регистриран! Регистрирайте се БЕЗПЛАТНО, за да използвате услугите на сайта!

   Рубрики
 
 
 
 

 Форуми
» SEO и оптимизация
» Всичко за PHP и Perl
» Всичко за C, C++ и .NET
» Всичко за Java и JSP
» Всичко за SQL и MySQL
» Всичко за XHTML и CSS
» Презентация на сайтове
 Преобразуване на Типовете
  1. Преобразуване с метода на отрязването
  2. Преобразуване чрез конструктор
     
Автор  eminem (01.03.2005 23:59)  съобщение до автора
Погледнат  4563 пъти  добави към любими
Оценка  добави коментар
Гласове  1  изпрати на приятел
Коментари  (1)  абонирай се за C-Cplusplus
    Страница 2 / 2

 



Преобразуване чрез конструктор

Всеки конструктор (извикан явно или неявно чрез един параметър) осъществява преобразуване от типа на параметъра в типа на класа.

 
Например за горния пример:

а=example(66);

ще доведе до създаването на временен обект от тип example и присвояване на този обект на a.

Конструкторът може да бъде извикан и неявно:

а=66;

Може да бъде създаден и специален конструктор за преобразуване (в случая, когато член-променлива/и са функция на параметър(ри)).
 
Пример
    
CODE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream.h>
class point
  
{ int x,y;       
    
public:
    
point(int c=0)            [color=blue]//конструктор за преобразуване[/color]
        {
x=c; y=5*c; }
    
void out()
        {
cout<<x<<” “<<y<<” “; }
   }
;                           
void main()
   {
point a; a.out();
    
a=point(12); a.out();
    
point b(6); b.out();
    
  
}

Резултати от изпълнение
       
0 0
12 60
6 30
           

Преобразуванията cast или конструктор се правят само в случаите, когато не е дефинирана операция за присвояване (=) в класа.
Пример илюстриращ изпълнението на операторната функция за присвояване за целите на преобразуването

CODE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream.h>
class point
  
{ int x,y;
    
public:
    
point(int a=0,int b=0)
       {
x=a; y=b; cout<<”конструкторn”; }
 
    
point &operator =(point &p)        [color=blue]//дефинция на функция[/color]
     {
x=p.x; y=p.y;                [color=blue]//за присвояване клас->клас[/color]
      
cout<<"присвояване point->pointn";           
      
return *this;
    
}
    
point &operator=(int n)            [color=blue]//дефиниция на функция[/color]
     {
x=n;y=0;                    //за присвояване int->клас
      
cout<<"присвояване int->pointn";
      
return *this;       
    
}
  }
;
void main()                        //Резултати от изпълнение
   
{ point a(1,2);                //конструктор
     
a=12;                    //присвояване int->point
      point b
;                    //конструктор
     
b=a;                    //присвояване point->point
   
}


Пример  за преобразуване на тип клас (point) в друг тип клас (complex) чрез конструктор за преобразуване

CODE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream.h>
class point;
class complex
  
{ double real,imag;
    
public:
    
complex(double r=0,double =0)    //конструктор
      
{ real=r; imag=i; }
    
complex(point);            //декларация на конструктор     void out()                //за преобразуване
      
{ cout<<real<<”+”<<imag<<”In”;
 }
;                       
class point
  
{ int x,y;
    
public:
    
point(int a=0,int b=0)
       {
x=a; y=b; }
    
friend complex::complex(point);
  
};
compex::complex(point p)        //дефиниция на конструктор
  
{ real=p.x; imag=p.y; }        //за преобразуване
void main()
   {
point a(3,5);
    
complex c(a);            //дефинира се обект
    
c.out();                //и се извиква конструктор
  
}                        //за преобразуване


Резултати от изпълнение

3+5i

Автор: Янко Димитров



 << Предишна страница  


Ключови думи: c C++ преобразуване тип метод обект функция


Още уроци от тази рубрика


 
  • Подобни теми от myLinks
 

 1 посетител чете този урок (0 потребители и 1 гост)  
Активни потребители: ---
   
  

Еmail  
 

Tired of defining five times the same function? One definition for int type parameters, one definition for double type parameters, one definition for float type parameters... Didn't you forget one type? What if a new data type is used? No problem: the C++ compiler is capable of generating automatically every version of the function that is necessary! Just tell him how the function looks like by declaring a template function:



using namespace std;#include <iostream>template <class ttype>ttype min (ttype a, ttype b){   ttype r;   r = a;   if (b < a) r = b;   return r;}int main (){   int i1, i2, i3;   i1 = 34;   i2 = 6;   i3 = min (i1, i2);   cout << "Most little: " << i3 << endl;   double d1, d2, d3;   d1 = 7.9;   d2 = 32.1;   d3 = min (d1, d2);   cout << "Most little: " << d3 << endl;   cout << "Most little: " << min (d3, 3.5) << endl;   return 0;}


The function min is used three times in above program yet the C++ compiler generates only two versions of it: int min (int a, int b) and double min (double a, double b). That does the job for the whole program.

Would you have tried something like calculating min (i1, d1) the compiler would have reported that as an error. Indeed the template tells both parameters are of the same type.

You can use a random number of different template data types in a template definition. And not all parameter types must be templates, some of them can be of standard types or user defined (char, int, double...). Here is an example where the min function takes parameters of any, possibly different, types and outputs a value that has the type of the first parameter:



using namespace std;#include <iostream>template <class type1, class type2>type1 min (type1 a, type2 b){   type1 r, b_converted;   r = a;   b_converted = (type1) b;   if (b_converted < a) r = b_converted;   return r;}int main (){   int i;   double d;   i = 45;   d = 7.41;   cout << "Most little: " << min (i, d) << endl;   cout << "Most little: " << min (d, i) << endl;   cout << "Most little: " << min ('A', i) << endl;   return 0;}


мисля че това е близко до темата
повече инго тук: http://www.4p8.com/eric.brasseur/cppcen.html#l1

  irrefutable на 09.03.2005 18:44

 

 
  • Интересно от Софтуер
 



IT-PLACE.NET © 2004 - 2008