请参见以下代码:
中使用的'void *'类型的指针#include <iostream> #include <stdlib.h> using namespace std; class ex { public: int x; int y; double z; ex() { cout<<"constructor"; } ~ex() { cout<<"destructor"; } }; int main() { void *pt=malloc(sizeof(ex)*2); ex *p,*p1; p=new(pt) ex(); p1=new(pt+sizeof(ex)) ex(); p->x=4444; p->y=3333; p->z=65.87879898; p1->x=55555; p1->y=66666; p1->z=6666.6666666; cout<<"\nP: "<<p->x<<"\n"<<p->y<<"\n"<<p->z<<"\n"; cout<<"\np1: "<<p1->x<<"\n"<<p1->y<<"\n"<<p1->z<<"\n"; p->~ex(); p1->~ex(); free(pt); return 0; }
它显示警告。警告:算术[-Wpointer-arith] |
有任何方法可以克服这个问题,或者代码是错误的。注意:该代码显示正确的输出。
谢谢您的帮助。
请参见以下代码:#include
此行有问题:
pt+sizeof(ex)