注册 登录
编程论坛 C++教室

创建空间

shaoyuan 发布于 2008-09-11 16:21, 683 次点击
#include<stdlib.h>
#include<iostream.h>
class shaoyuan{
public:
    shaoyuan(int y){ x=y;
        cout<<"begin\n";
    }   void sy(){cout<<"adfasdfas"<<"   "<<x<<endl;}
    ~shaoyuan(){
        cout<<"end\n";
    }private: int x;
};
void main(){
    int *p=(int *)malloc(sizeof(int));
         shaoyuan *p1=(shaoyuan*)malloc(sizeof(shaoyuan(10)));
    p1->sy(); free (p1);
}
请问为什么在执行shaoyuan *p1=(shaoyuan*)malloc(sizeof(shaoyuan(10)));时不会执行构造函数而且在释放空间的时候也不会执行析构函数,还有就是p1->sy(); 输出的x的值不是10,谢谢!!!
7 回复
#2
blueboy820062008-09-11 18:19
为什么要执行构造函数和析构函数啊??
你有创建过该类类型的对象吗?

你加这句看看...
shaoyuan a(2);
#3
huihexiang2008-09-12 09:24
sizeof(shaoyuan(10))
跟sizeof(shaoyuan(9))没区别
#4
huihexiang2008-09-12 09:40
//创建空间后要赋值,*p才会有意义
#include<stdlib.h>
#include<iostream.h>
class shaoyuan{
public:
    shaoyuan(int y)
    { x=y;
        cout<<"begin\n";
    }   
    void sy(){cout<<"adfasdfas"<<"   "<<x<<endl;}
    ~shaoyuan(){
        cout<<"end\n";
    }
private: int x;
};
void main(){
    int *p=(int *)malloc(sizeof(int));
    shaoyuan *p1=(shaoyuan*)malloc(sizeof(shaoyuan));
    *p1=shaoyuan(10);
    p1->sy();
    free (p1);
}
#5
BlueMouse2008-09-12 09:44
shaoyuan *p1=(shaoyuan*)malloc(sizeof(shaoyuan(10)));

这个直观去理解就是分配一块内存强制转换为 shaoyuan类型的指针然后把申请到的地址存入指针p1中去! 当然跟构造函数没有关系了!

这样做不行吗?

shaoyuan *p1= new shaoyuan(10);
#6
huihexiang2008-09-12 09:53
再将  free(p1);
改为  delete p1;
#7
zhifeng20072008-09-12 10:08
int *p=(int *)malloc(sizeof(int)); 这句有什么意义吗?
#8
BlueMouse2008-09-12 14:04
哎!真是倒了!
哎!
1