заголовок
#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 << testing.size() << endl;), мой тест test.size() последовательно выводит 0, когда теоретически это должно быть 6, поскольку я назначаю sz и колпачок в функциях IntVector. Любые идеи о том, почему он выводит 0?
Похоже, вы создаете временное, которое отбрасывается здесь:
IntVector(6, 4);
Вы хотите создать объект, например:
IntVector testing(6, 4);
Тогда это работает.
main()
:IntVector(6, 4);
Я хотел бы знать, гдеtesting
входит в картину.