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

请问这段代码为什么编译正常,运行时却出错!

haitao9999 发布于 2009-10-21 21:39, 636 次点击
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;
}
3 回复
#2
shiyuehai2009-10-22 08:49
第一行貌似少了个#号
#3
debroa7232009-10-22 22:07
    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]已经存在,也要先将之前的指针删除,才能赋值新的,否则造成内存漏露。
#4
Tomato_fan2009-10-22 23:10
楼上正确,vector<counted*>  countArray,这句定义之后,countArray还是空的,不能用countArray[i],可以用push_back
1