2014-02-22 61 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。 –