C++的一个小问题?
class CBase
{
public:
CBase *pointer;
public:
CBase()
{
cout<<"cbase constructor!"<<endl;
//pointer=this;
}
virtual void Output1()
{
cout<<"output cbase class!"<<endl;
}
};
class CDerived :public CBase
{
public:
void Output1()
{
//pointer=this;
cout<<"output CDerived class!"<<endl;
}
};
int main()
{
CBase base;
base.pointer->Output1();
CDerived derived;
derived.pointer->Output1();
return 0;
}
编译链接都没问题,就运行有错误提示。
我的问题就是为何用pointer指针调用函数就出问题了。我试了简单程序,不是指针没初始化的问题。如果virtual关键字删掉,运行就没问题了,为何加了virtual就有问题了呢?
[解决办法]
不赋值是野指针,读不了虚函数表,取地址是访问非法内存
[解决办法]
pointer是野指针,那它本来包含的虚函数表__vfptr也是野指针,而函数必须从它那得到函数地址,因此读它的值时就访问非法地址了,所以crash
[解决办法]
如需要阅读该回复,请登录或注册CSDN!
如需要阅读该回复,请登录或注册CSDN!