运行此程序时出现“分段错误”。请区分以下两个程序
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
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();
}
- 输出
f in xxx
g in xxx
f in yyy
g in yyy