什麼時候可以不用例項化物件就可以呼叫類中成員函式
阿新 • • 發佈:2019-01-23
對於一個類A,對於這個定義((A*)0)或者 A *p = NULL 都可以呼叫類中的那些成員函式。
第一種情況:非靜態成員函式沒有使用類的非靜態資料成員,呼叫的其他非靜態成員函式也不能使用類的非靜態資料成員
#include <iostream> using namespace std; class A { public: void fun1() { cout<<"fun1"<<endl; fun2(); //如果fun2函式內部呼叫了資料成員a,則會呼叫失敗 } void fun2() { cout<<"fun2"<<endl; //a = 1; } private: int a; int b; }; int main() { A *p = NULL; p->fun1(); }
第二種情況:非靜態成員呼叫類的靜態資料成員。
#include <iostream> using namespace std; class A { public: void fun1() { cout<<"fun1"<<endl; a = 3; cout<<"a = "<<a<<endl; } private: static int a; int b; }; int A::a = 0; int main() { A *p = NULL; p->fun1(); }
第三種情況:類的靜態成員函式
#include <iostream> using namespace std; class A { public: static void fun1() { cout<<"fun1"<<endl; a = 3; cout<<"a = "<<a<<endl; } private: static int a; int b; }; int A::a = 0; int main() { A *p = NULL; p->fun1(); }