運行此程序時出現「分段錯誤」。輸出多態概念
f in xxx
g in xxx
f in yyy
Segmentation fault
但根據多態性概念,同樣的問題
class xxx{
public: virtual void f(){cout<<"f in xxx"<<endl;} //virtual function
virtual void g(){cout<<"g in xxx"<<endl;} //virtual function
};
class yyy:public xxx{ //yyy is derived from xxx
public: virtual void f(){cout<<"f in yyy"<<endl;}
void g(){cout<<"g in yyy"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1,*x;
yyy y1;
x=&x1;
x->f();
x->g();
x=(xxx*) &y1; //parent class pointer having derived class address
x->f();
x->g();
}
- - 請在下面兩個程序
class xxx{
public: virtual void f(){cout<<"f in xxx"<<endl;} //virtual function
virtual void g(){cout<<"g in xxx"<<endl;} //virtual function
};
class yyy{ //yyy has no relation with xxx at this context
public: virtual void f(){cout<<"f in yyy"<<endl;} //virtual function but no relation with xxx class
void g(){cout<<"g in yyy"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1,*x;
yyy y1;
x=&x1;
x->f();
x->g();
x=(xxx*) &y1; //one class pointer containing another class object address
x->f();
x->g();
}
的區分輸出
f in xxx
g in xxx
f in yyy
g in yyy
你不需要打擾它。只要做:x = &y1; – 2013-03-14 19:08:04
有什麼問題? – 2013-03-14 19:08:06
尊敬的傑米格雷..嘗試你的想法時出現錯誤... x = &y1; //錯誤:不能轉換âyyy*â在xxx *â在作業謝謝... – 2013-03-27 05:48:47