标题:请问这段代码为什么编译正常,运行时却出错!
只看楼主
haitao9999
Rank: 2
等 级:论坛游民
帖 子:30
专家分:39
注 册:2006-4-10
结帖率:33.33%
已结贴  问题点数:15 回复次数:3 
请问这段代码为什么编译正常,运行时却出错!
include <iostream>
#include <vector>
using namespace std;

class counted{
    int id;
    static int count ;
public:
    counted():id(count++){
    cout<<id<<endl<<"it's being created"<<endl;
    }
    ~counted(){
    cout<<id--<<endl<<"it's being destroyed"<<endl;
    }
};

int counted::count = 0;

int main(){
    vector<counted*>  countArray;
    for(int i=0;i<5;i++)
        {
            if((countArray[i] = new counted)==0)
                cerr<<"内存申请失败";
    }
    return 1;
}
搜索更多相关主题的帖子: 编译 运行 代码 
2009-10-21 21:39
shiyuehai
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:96
专家分:116
注 册:2009-9-4
得分:5 
第一行貌似少了个#号
2009-10-22 08:49
debroa723
Rank: 10Rank: 10Rank: 10
等 级:贵宾
威 望:23
帖 子:862
专家分:1954
注 册:2008-10-12
得分:5 
    vector<counted*>  countArray;
    counted* tempP = NULL;
    for(int i=0;i<5;i++)
    {
        tempP =  new counted();
        if( tempP == 0 )
        {
            cerr<<"内存申请失败";
        }else
        {
            countArray.push_back(tempP);
        }
    }
    char ch='y';
    cin>>ch;

在main函数里的修改。
vector的使用方法看看STL相关的书籍。
如果countArray[i]已经存在,也要先将之前的指针删除,才能赋值新的,否则造成内存漏露。
2009-10-22 22:07
Tomato_fan
Rank: 2
等 级:论坛游民
帖 子:9
专家分:65
注 册:2009-10-18
得分:5 
楼上正确,vector<counted*>  countArray,这句定义之后,countArray还是空的,不能用countArray[i],可以用push_back
2009-10-22 23:10



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-289423-1-1.html




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

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