我的大小函数返回0?

时间:2014-02-22 01:57:24

标签: c++

#ifndef INTVECTOR_H
#define INTVECTOR_H

using namespace std;
class IntVector{
private:
    unsigned sz;
    unsigned cap;
    int *data;
public:
    IntVector();
    IntVector(unsigned size);
    IntVector(unsigned size, int value);
    unsigned size() const;
};
#endif 

#include "IntVector.h"
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;



IntVector::IntVector(){
    sz = 0;
    cap = 0;
    data = NULL;
}

IntVector::IntVector(unsigned size){
    sz = size;
    cap = size;
    data = new int[sz];
    *data = 0;
}

IntVector::IntVector(unsigned size, int value){
    sz = size;
    cap = size;
    data = new int[sz];
    for(unsigned int i = 0; i < sz; i++){
        data[i] = value;
    }
}

unsigned IntVector::size() const{
    return sz;
}

当我在Main中测试我的函数时,(IntVector(6,4);     cout&lt;&lt; testing.size()&lt;&lt; endl;),我的testing.size()测试在理论上应该是6时始终输出0,因为我在IntVector函数中分配了sz和cap。关于为什么输出0的任何想法?

1 个答案:

答案 0 :(得分:3)

看起来你正在创建一个在此丢弃的临时文件:

IntVector(6, 4); 

您想要创建一个对象,如下所示:

IntVector testing(6, 4); 

然后works