2014-02-22 63 views
0

我的尺寸函数返回0?

#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; 
} 

当我在主测试我的功能,(intVector的(6,4); COUT < < testing.size()< < ENDL;),我的当我在IntVector函数中分配sz和cap时,testing.size()测试在理论上应该是6时始终输出0。任何想法,为什么它输出0?

+1

如果main()是这样的:'IntVector(6,4);',我想知道'testing'在哪里出现。 – WhozCraig

回答

3

看起来你正在创建一个临时被丢弃在这里:

IntVector(6, 4); 

你想创建一个对象,像这样:

IntVector testing(6, 4); 

然后works

+0

我明白了。我把它作为IntVector测试;但我想当你这样做时Visual Studio不喜欢它。 – user3314899

+0

@ user3314899这不是由于Visual Studio。 –