因为C++中的所有虚函数都存储在V-table中.在虚函数的情况下发生重叠. 我想问一下,我们可以通过哪种方式直接从表中调用虚函数,并且能够确定V-table包含哪些函数.
这里有人回答说我们无法获得析构函数的函数指针, 然后虚函数如何在下面的代码中工作.虚拟构造函数是否保存在虚拟表中?如果没有那么虚拟机构在虚拟析构函数的情况下如何工作?
#include<stdio.h>
class Base
{
public:
Base()
{
printf("C-Base\n");
}
virtual ~Base()
{
printf("Base\n");
}
};
class Derived:public Base
{
public:
Derived()
{
printf("C-DErived\n");
}
~Derived()
{
printf("DErived\n");
}
};
int main()
{
Base *b=new Derived();
delete b;
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中,如果我们不在Base类中使用虚函数,则Destructor Derived类析构函数不会被调用.
该解决方案基于对计算机的非常重要的观察.我系统中的指针大小为8个字节.这个结构的大小
struct ll1
{
int data;
struct ll1 *next;
};
Run Code Online (Sandbox Code Playgroud)
是16 bytes.作为具有多个成员的结构指针,将始终具有一些尾随零.这是由于内存对齐.所以即时尝试使用剩下的4个字节来存储被访问的标志.当我为这四个字节分配0时,它不会给出错误,但是当我指定除零以外的值时,它会在下面的代码中给出分段错误.PLZ有人解释为什么会这样吗?
#include<stdio.h>
#include<stdlib.h>
struct ll1
{
int data;
struct ll1 *next;
};
typedef struct ll1 ll;
void create(ll **root)
{
int t=1;
printf("\nEnter node value 0 if end:");
scanf("%d",&t);
if(t)
{
(*root)=(ll*)malloc(sizeof(ll)) ;
(*root)->data=t;
create(&(*root)->next);
}
else
(*root)=NULL;
}
int main()
{
ll *node;
create(&node);
ll *temp=node,*temp2=node;
int j,size=0;
/*printing 4-4 bytes of the node */
while(temp->next)
{
size++;
int *p=(int *)temp;
printf("\n%d %d %d %d",*(p),*(p+1),*(p+2),*(p+3));
*(p+3)=0; …Run Code Online (Sandbox Code Playgroud)