[cpp] view plaincopy
- class Point
- {
- public:
- void init()
- {
- }
- static void output()
- {
- }
- };
- void main()
- {
- Point::init();
- Point::output();
- }
結論1:不能通過類名來調用類的非靜態成員函數。
[cpp] view plaincopy
- void main()
- {
- Point pt;
- pt.init();
- pt.output();
- }
結論2:類的對象可以使用靜態成員函數和非靜態成員函數。
[cpp] view plaincopy
- #include <stdio.h>
- class Point
- {
- public:
- void init()
- {
- }
- static void output()
- {
- printf("%d\n", m_x);
- }
- private:
- int m_x;
- };
- void main()
- {
- Point pt;
- pt.output();
- }
結論3:靜態成員函數中不能引用非靜態成員。
[cpp] view plaincopy
- class Point
- {
- public:
- void init()
- {
- output();
- }
- static void output()
- {
- }
- };
- void main()
- {
- Point pt;
- pt.output();
- }
結論4:類的非靜態成員函數可以調用用靜態成員函數,但反之不能。
[cpp] view plaincopy
- #include <stdio.h>
- class Point
- {
- public:
- Point()
- {
- m_nPointCount++;
- }
- ~Point()
- {
- m_nPointCount--;
- }
- static void output()
- {
- printf("%d\n", m_nPointCount);
- }
- private:
- static int m_nPointCount;
- };
- void main()
- {
- Point pt;
- pt.output();
- }
結論5:類的靜態成員變量必須先初始化再使用。
:
[cpp] view plaincopy
- #include <stdio.h>
- #include <string.h>
- const int MAX_NAME_SIZE = 30;
-
- class Student
- {
- public:
- Student(char *pszName);
- ~Student();
- public:
- static void PrintfAllStudents();
- private:
- char m_name[MAX_NAME_SIZE];
- Student *next;
- Student *prev;
- static Student *m_head;
- };
-
- Student::Student(char *pszName)
- {
- strcpy(this->m_name, pszName);
-
- //建立雙向鏈表,新數據從鏈表頭部插入。
- this->next = m_head;
- this->prev = NULL;
- if (m_head != NULL)
- m_head->prev = this;
- m_head = this;
- }
-
- Student::~Student ()//析構過程就是節點的脫離過程
- {
- if (this == m_head) //該節點就是頭節點。
- {
- m_head = this->next;
- }
- else
- {
- this->prev->next = this->next;
- this->next->prev = this->prev;
- }
- }
-
- void Student::PrintfAllStudents()
- {
- for (Student *p = m_head; p != NULL; p = p->next)
- printf("%s\n", p->m_name);
- }
-
- Student* Student::m_head = NULL;
-
- void main()
- {
- Student studentA("AAA");
- Student studentB("BBB");
- Student studentC("CCC");
- Student studentD("DDD");
- Student student("MoreWindows");
- Student::PrintfAllStudents();
- }