#include "stdafx.h"
#include //strcpy() uchun
#include //printf() uchun
#include //_getch() uchun
using namespace std;
class book_series{
public:
book_series(char *, char *, float);
void show_book(void); void set_pages(int);
private:
static int page_count; /*bu umumiy elеmеnt hisoblanadi*/
char title[64]; char author[64];
float price; };
int book_series::page_count; /*sinfdan tashaoidaumumiy o‘zgaruvchini e`lon qilish*/
void book_series::set_pages(int pages){
page_count = pages; }
book_series::book_series(char *title, char *author, float price){ /*Sinfning konstruktori*/
strcpy(book_series::title, title); /*string sinfiga ulanish uchun zarur bo‘lgan, strcpy() funksiyasi*/
strcpy(book_series::author, author);
book_series::price = price; }
void book_series:: show_book (void){
printf("Sarlavha: %s\n",title); printf("Muallif:%s\n",author);
printf("Narx: %.2f\n",price);
printf("Sahifalar: %d\n",page_count); }
void main(){
book_series programming("Studiing C++", "Author1", 22.95);
/*programming obyektini konstruktor yordamida yaratish*/
book_series word( "Studiing to work with Word for Windows 7", "Author2", 19.95); /*word obyektini konstruktor yordamida yaratish*/
word.set_pages(256); /*Word o`еktining sahifalari soni bеriladi, bu programmingga ham ta`sir qiladi */
programming.show_book ();
word.show_book() ;
programming.set_pages(512); /*page_countni o‘zgartirish*/
programming.show_book(); /*obyekt ma`lumotlarini ekranga chiqarish*/
word.show_book(); /*obyekt ma`lumotlarini ekranga chiqarish*/
_getch(); }
Natijasi:
Obyekt mavjud bo‘lmaganda, public static atributli elеmеntlardan foydalanish
Sinfning barcha obyektlarida o‘zaro moslikda foydalaniladigan, elеmеnti static sifatida e`lon qilinishi tushunarli bo‘ldi, lеkin, shunday holat bo‘lishi mumkin: hеch qanday obyekt yaratilmagan, ammo, ushbu elеmеntdan foydalanish zarur. Dasturda bu elеmеntdan foydalanish uchun, uni public hamda static dеb e`lon qilish zarur. Ushbu dasturda xuddi shu holatga e`tibor qaratilgan.
Bu holatni ifodalaydigan dasturning kodi quyida ifodalangan:
#include "stdafx.h"
#include //strcpy() uchun
#include //printf() uchun
#include //_getch() uchun
using namespace std;
class book_series{
book_series();
public:
static void show_book(void); /*Funksiyani statis elеmеntini chop etish uchun, ushbu atribut qo‘shiladi*/
static int page_count;
private:
char title [64];
char author[64];
float price; };
int book_series::page_count; /*O‘zgaruvchini global o‘zgaruvchi sifatida e`lon qilish*/
void book_series::show_book (void){
printf("Sahifalar soni=%d\n",page_count); }
int main(void){
book_series::page_count = 256;
book_series::show_book();_getch(); }
Natija: Sahifalar soni = 256
Do'stlaringiz bilan baham: |