logo

C++ סטטי

ב-C++, static היא מילת מפתח או משנה השייכת למופע מסוג type not. אז מופע אינו נדרש לגשת לחברים הסטטיים. ב-C++, סטטי יכול להיות שדה, שיטה, בנאי, מחלקה, מאפיינים, אופרטור ואירוע.


יתרון של מילת מפתח סטטית C++

יעיל בזיכרון: עכשיו אנחנו לא צריכים ליצור מופע לגישה לאיברים הסטטיים, אז זה חוסך זיכרון. יתר על כן, הוא שייך לסוג, כך שהוא לא יקבל זיכרון בכל פעם כאשר מופע נוצר.


C++ שדה סטטי

שדה שמוכרז כסטטי נקרא שדה סטטי. שלא כמו שדה מופע שמקבל זיכרון בכל פעם שאתה יוצר אובייקט, יש רק עותק אחד של שדה סטטי שנוצר בזיכרון. זה משותף לכל האובייקטים.

מתי q2 מתחיל

הוא משמש כדי להפנות את הרכוש המשותף של כל האובייקטים כגון rateOfInterest במקרה של חשבון, companyName במקרה של עובד וכו'.


דוגמה לשדה סטטי C++

בואו נראה את הדוגמה הפשוטה של ​​שדה סטטי ב-C++.

אלגוריתמים חיפוש בינארי
 #include using namespace std; class Account { public: int accno; //data member (also instance variable) string name; //data member(also instance variable) static float rateOfInterest; Account(int accno, string name) { this-&gt;accno = accno; this-&gt;name = name; } void display() { cout&lt; <accno<< '<<name<< ' '<<rateofinterest<<endl; } }; float account::rateofinterest="6.5;" int main(void) { account a1="Account(201," 'sanjay'); creating an object of employee a2="Account(202," 'nakul'); a1.display(); a2.display(); return 0; < pre> <p>Output:</p> <pre> 201 Sanjay 6.5 202 Nakul 6.5 </pre> <hr> <h2>C++ static field example: Counting Objects</h2> <p>Let&apos;s see another example of static keyword in C++ which counts the objects.</p> <pre> #include using namespace std; class Account { public: int accno; //data member (also instance variable) string name; static int count; Account(int accno, string name) { this-&gt;accno = accno; this-&gt;name = name; count++; } void display() { cout&lt; <accno<<' '<<name<<endl; } }; int account::count="0;" main(void) { account a1="Account(201," 'sanjay'); creating an object of a2="Account(202," 'nakul'); a3="Account(203," 'ranjana'); a1.display(); a2.display(); a3.display(); cout<<'total objects are: '< <account::count; return 0; < pre> <p>Output:</p> <pre> 201 Sanjay 202 Nakul 203 Ranjana Total Objects are: 3 </pre></accno<<'></pre></accno<<>

דוגמה לשדה סטטי C++: ספירת אובייקטים

בוא נראה דוגמה נוספת למילת מפתח סטטית ב-C++ שסופרת את האובייקטים.

 #include using namespace std; class Account { public: int accno; //data member (also instance variable) string name; static int count; Account(int accno, string name) { this-&gt;accno = accno; this-&gt;name = name; count++; } void display() { cout&lt; <accno<<\' \'<<name<<endl; } }; int account::count="0;" main(void) { account a1="Account(201," \'sanjay\'); creating an object of a2="Account(202," \'nakul\'); a3="Account(203," \'ranjana\'); a1.display(); a2.display(); a3.display(); cout<<\'total objects are: \'< <account::count; return 0; < pre> <p>Output:</p> <pre> 201 Sanjay 202 Nakul 203 Ranjana Total Objects are: 3 </pre></accno<<\'>