Dustlar sonini chegaralash
C++ tilida do’stona sinfning hamma funktsiyalari balki ba'zi funktsiyalariga hususiy elementlarga murojaat huquqini berish mumkindir. Misol uchun librarian sinfining change_catalog va get_catalog funktsiyalariga book sinfing hususiy elementlariga murojaat qilish imkonini berish lozim bo’lsin. U holda book sinfida bu huquqni qo’yidagicha ko’rsatish mumkindir:
class book
{
public:
book(char *, char *, char *);
void show_book(void);
friend char *librarian::get_catalog(book);
friend void librarian: :change_catalog( book *, char *);
private:
char title[64];
char author[ 64 ];
char catalog[64];
};
Bu misoldan ko’rinib turibdiki friend operatorlari do’stona funktsiyalarning Tula prototiplariga egadirlar.Dustona funktsiyalar. Agar dasturda bir sinfdan ikkinchi sinfga murojaat mavjud bo’lsa va sinf ta'riflari tartibi notug’ri keltirilgan bo’lsa sintaksis hato kelib chiqadi. Misolda book sinfi librarian sinfida aniqlangan funktsiyalar prototiplaridan foydalanadi. Shuning uchun librarian sinfi ta'rifi book sinfi ta'rifidan oldin kelishi kerak. Lekin librarian sinfi tahlil qilinsa u book sinfiga murojaat qilishini aniqlash mumkin:
class librarian
{
public:
void change_catalog(book *, char *);
char *get_catalog(book);
};
Dasturda book sinfi ta'rifini librarian sinfi ta'rifidan oldin qo’yish mumkin bo’lmaganligi uchun, C++ oldin book sinfini e'lon qilib so’ngra keyinroq ta'riflash imkonini beradi. Qo’yida qanday amalga oshirish mumkinligi ko’rsatilgan:
class book; //
Qo’yidagi LIMITFRI.CPP dasturda do’stona funktsiyalarodan foydalanilgan. Sinflar tap'riflari tartibiga e'tibor bering:
#include
#include
class book;
class librarian
{
public:
void change_catalog(book *, char *);
char *get_catalog(book);
};
class book
{
public:
book(char *, char *, char *) ;
void show_book (void);
friend char *librarian::get_catalog(book);
friend void librarian::change_catalog( book *, char *);
private:
char title[64];
char author[64];
char catalog[64];
};
book::book(char *title, char *author, char *catalog)
{
strcpy(book::title, title);
strcpy(book::author, author);
strcpy(book::catalog, catalog);
}
void book::show_book(void)
{
cout << "Nazvanie: " << title << endl;
cout << "Avtor: " << author << endl;
cout << "Katalog: " << catalog << endl;
}
void librarian::change_catalog(book *this_book, char *new_catalog)
{
strcpy(this_book->catalog, new_catalog) ;
}
char *librarian::get_catalog(book this_book)
{
static char catalog[64];
strcpy(catalog, this_book.catalog);
return(catalog) ;
}
void main(void)
{
book programming( "Uchimsya programmirovat' na C++", "Jamsa", "P101");
librarian library;
programming.show_book();
library.change_catalog(&programming, "Legkiy C++ 101");
programming.show_book();
}
Dasturda book sinfi mavjudligi e'lon qilinadi. Shuning uchun librarian sinfi hali ta'riflanmagan sinfga murojaat qilishi mumkin.
Do'stlaringiz bilan baham: |