++C מפרקים וירטואלים.

selalerer

New member
++C מפרקים וירטואלים.

כתבתי את הקוד הבא (לא חייבים לקרוא את כולו, אפשר לדלג לשאלה):
include <iostream> using namespace std; class father { protected: int num; public: father(){static int c=0;father::num=++c;cout<<"father ctor:eek:bject number "<<father::num<<endl;} ~father(){cout<<"father dtor:eek:bject number "<<father::num<<endl;} }; class son:public father { private: int num; public: son(){static int c=0;son::num=++c;cout<<"son of "<<father::num<<" ctor:son number "<<son::num<<endl;} ~son(){cout<<"son of "<<father::num<<" dtor:son number "<<son::num<<endl;} }; int main(int argc, char *argv[]) { father f1; son s1; cin.get(); return 0; }​
וקימפלתי ב++g גרסה 2.95.2 והפלט אומר שגם הבנאי וגם המפרק של האב רצו כאשר יצרתי אובייקט בן. עם הבנאי אין לי בעיה, אבל הזהירו לעשות תמיד מפרק וירטואלי בכדי שירוץ במחלקות יורשות, ופה הוא רץ בכל מקרה, אפילו שהוא לא וירטואלי, אז בשביל מה להכריז וירטואלי? תודה, סלע.
 

annefan

New member
הדוגמא שלך לא טובה

א. זה FAQ ב. תבדוק את הקוד הזה כה-DTOR של האבא וירטואלי ולא וירטואלי.
#include <iostream> using namespace std; class father { protected: int num; public: father(){static int c=0;father::num=++c;cout<<"father ctor:eek:bject number "<<father::num<<endl;} ~father(){cout<<"father dtor:eek:bject number "<<father::num<<endl;} }; class son:public father { private: int num; public: son(){static int c=0;son::num=++c;cout<<"son of "<<father::num<<" ctor:son number "<<son::num<<endl;} ~son(){cout<<"son of "<<father::num<<" dtor:son number "<<son::num<<endl;} }; int main(int argc, char *argv[]) { son * s2 = new son; father * f2 = s2; cout << "after CTOR" << endl; delete f2; return 0; }​
 

selalerer

New member
אהה, עם מצביע לאב.

ידעתי את זה אבל שכחתי
 
למעלה