虚函数表只是一个索引表,在类的第一个地址中存放。
Base b; &b这个操作是将虚函数表指针的地址暴露出来。
(int *)&b 是将&b转换为int型指针,((int *)&b) 就是虚函数表的指针,而 ((int *)&b)的值就是 &b的值
所以 *(int *)&b 就是 ((int *)&b)指向的值,也就是 虚函数表 的地址,所以(int*)*(int *)&b就是指向 虚函数表 的地址,也就是表的第一个格子的地址,第一个格子中存放的是 第一个虚函数地址
所以 *(int *)*(int *)&b 调用的就是第一个虚函数地址的值,再通过转换(int*)*(int *)*(int *)&b 就就变成了指向 第一个虚函数 的指针 *(int*)*(int *)*(int *)&b 就是 第一个虚函数 可以用函数指针来调用这个函数的逻辑
class ICBase{
public:
/*修改接口为纯虚函数*/
virtual void my()=0;
virtual void you()=0;
};
class CBase : public ICBase
{
public:
void my()
{
cout << "父类" << endl;
}
void you()
{
cout << "父类1" << endl;
}
void he()
{
cout<<"父类2"<<endl;
}
};
class CDerivedA : public CBase
{
public:
void my()
{
cout << "子类" << endl;
}
void you()
{
cout << "子类1" << endl;
}
void he()
{
cout<<"子类2"<<endl;
}
};
int main()
{
CBase* b=new CDerivedA;
CBase* ptr=b;
ptr->my();
ptr->you();
ptr->he();
return 0;
}
以上,输出为:
子类
子类1
父类2
修改成
class ICBase
{
public:
/*修改接口为虚函数*/
virtual void my(){};
virtual void you(){};
};
class CBase : public ICBase
{
public:
void my()
{
cout << "父类" << endl;
}
void you()
{
cout << "父类1" << endl;
}
void he()
{
cout<<"父类2"<<endl;
}
};
class CDerivedA : public CBase
{
public:
void my()
{
cout << "子类" << endl;
}
void you()
{
cout << "子类1" << endl;
}
void he()
{
cout<<"子类2"<<endl;
}
};
int main()
{
CBase* b=new CDerivedA;
CBase* ptr=b;
ptr->my();
ptr->you();
ptr->he();
return 0;
}
以上,输出为:
子类
子类1
父类2
修改成
class ICBase
{
public:
/*修改接口为函数定义*/
void my();
void you();
};
class CBase : public ICBase
{
public:
void my()
{
cout << "父类" << endl;
}
void you()
{
cout << "父类1" << endl;
}
void he()
{
cout<<"父类2"<<endl;
}
};
class CDerivedA : public CBase
{
public:
void my()
{
cout << "子类" << endl;
}
void you()
{
cout << "子类1" << endl;
}
void he()
{
cout<<"子类2"<<endl;
}
};
int main()
{
CBase* b=new CDerivedA;
CBase* ptr=b;
ptr->my();
ptr->you();
ptr->he();
return 0;
}
输出为:
父类
父类1
父类2