| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 683 人关注过本帖, 1 人收藏
标题:创建空间
只看楼主 加入收藏
shaoyuan
Rank: 1
等 级:新手上路
帖 子:69
专家分:0
注 册:2008-9-7
结帖率:100%
收藏(1)
 问题点数:0 回复次数:7 
创建空间
#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,谢谢!!!
搜索更多相关主题的帖子: 空间 
2008-09-11 16:21
blueboy82006
Rank: 5Rank: 5
来 自:幻想世界
等 级:贵宾
威 望:16
帖 子:1227
专家分:57
注 册:2007-7-23
收藏
得分:0 
为什么要执行构造函数和析构函数啊??
你有创建过该类类型的对象吗?

你加这句看看...
shaoyuan a(2);

2008-09-11 18:19
huihexiang
Rank: 1
等 级:新手上路
威 望:1
帖 子:11
专家分:0
注 册:2008-9-1
收藏
得分:0 
sizeof(shaoyuan(10))
跟sizeof(shaoyuan(9))没区别
2008-09-12 09:24
huihexiang
Rank: 1
等 级:新手上路
威 望:1
帖 子:11
专家分:0
注 册:2008-9-1
收藏
得分:0 
//创建空间后要赋值,*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);
}
2008-09-12 09:40
BlueMouse
Rank: 1
来 自:贵州
等 级:新手上路
威 望:1
帖 子:52
专家分:0
注 册:2008-9-6
收藏
得分:0 
shaoyuan *p1=(shaoyuan*)malloc(sizeof(shaoyuan(10)));

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

这样做不行吗?

shaoyuan *p1= new shaoyuan(10);
2008-09-12 09:44
huihexiang
Rank: 1
等 级:新手上路
威 望:1
帖 子:11
专家分:0
注 册:2008-9-1
收藏
得分:0 
再将  free(p1);
改为  delete p1;
2008-09-12 09:53
zhifeng2007
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2008-9-11
收藏
得分:0 
int *p=(int *)malloc(sizeof(int)); 这句有什么意义吗?
2008-09-12 10:08
BlueMouse
Rank: 1
来 自:贵州
等 级:新手上路
威 望:1
帖 子:52
专家分:0
注 册:2008-9-6
收藏
得分:0 
哎!真是倒了!
哎!
2008-09-12 14:04
快速回复:创建空间
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015503 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved