Jump to content
Sign in to follow this  
otai_g

Mintk Tlng Trackkan Program Ni

Recommended Posts

kawan2 aku ada 1 program dan output dia.tp x phm mcm mn output dia leh dpt mcm tu.mintk tng explain sikit drp hustler2 C++ kita kat sini knp output dia mcm tu.

// static members in classes
#include <iostream>
using namespace std;

class CDummy {
  public:
    static int n;
    CDummy () { n++; };
    ~CDummy () { n--; };
};

int CDummy::n=0;

int main () {
  CDummy a;
  CDummy b[5];
  CDummy * c = new CDummy;
  cout << a.n << endl;
  delete c;
  cout << CDummy::n << endl;
  return 0;
}
output dia
7
6

sumber coding : http://www.cplusplus.com/doc/tutorial/classes2.html

Share this post


Link to post
Share on other sites

static int n maknanya awak define n sebagai class variable, maknanya ianya wujud walaupun awak tak instantiate that class. So firt sekali

int CDummy::n=0;
n initially become 0 laa then first instantiation of CDummy :
CDummy a;
tengok ctor tu kan ada increment, so after ctor finish, n = 1 then u create array of CDummy dengan 5 elemens
CDummy b[5]
maknanya, after this, n = 6 (call ctor 5 times) after that, instantiation with new operator, same also
CDummy * c = new CDummy;

after this, n = 7

so u print n, kluar la n = 7

then u delete c, dtor for CDummy kena panggil, yang decrement n. maknanya now n = 6

so u print n, kluar laa n = 6

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...