Niezainicjalizowane pola klasy

0

Witam. Mam problem z konstrukcją obiektu. Bowiem wewnątrz konstruktora inicjalizuję randomową długość tablicy, a także samą tablicę z randomowymi wartościami. Kiedy wypisuję tablicę pod koniec konstruktora, to wszystko działa. Jednak gdy drugi raz wołam obiekt z klienta main(), przy metodzie "print()", okazuje się, że pole N jest równe 0. Jakieś pomysły? Wstawiam tylko fragment kodu, bo pozostałe metody są nieistotne ze względu na wczesne występowanie problemu.

Plik ArraySolver.h

 
/****************** Array Solver Class *********************/
class ArraySolver
{
private:
	int N;			//array[] length
	int *array;


public:
//Constructors
	ArraySolver();
	ArraySolver(int N);
	ArraySolver(int N, int *argArray);
//printing array
	void print() { print(0, N - 1); }
	void print(int, int);

/* other methods*/
};

Plik ArraySolver1.cpp

 
#include "Header.h"
#include "ArraySolver.h"

//Constructors
ArraySolver::ArraySolver(){
	srand((unsigned)time(NULL));
	ArraySolver(rand() % 15 + 5);//Randomize array[] length
}
ArraySolver::ArraySolver(int N){
	srand((unsigned)time(NULL));
	int *newArray = new int[N];
	for (int i = 0; i < N; i++)	//Fill array with random numbers
		newArray[i] = rand() % 100 - 50;
	ArraySolver(N, newArray);
}
ArraySolver::ArraySolver(int N, int *argArray){
	this->N = N;
	this->array = argArray;
	print();				/* tutaj N i array są poprawnie skontruowane*/
}
//Put array out
void ArraySolver::print(int start, int end){
	cout << "Array:";
	if (N == 0) {
		cout << "empty\n";
		throw new bad_array_new_length;
	}
	else{
		cout << "[" << array[start];
		for (int i = start + 1; i <= end; i++){
			cout << ", " << array[i];
		}
		cout << "]\n";
	}
}

Plik main.cpp

 
#include "Header.h"
#include "ArraySolver.h"

//CLIENT
int main(){
	ArraySolver solver;
	solver.print();	/*tu już N i array wyglądają jakby wywołał się jedynie domyślny konstruktor*/
	subarray maxSub1 = solver.maxSubarray();

	cout << "Maximum Subarray:";		
	solver.print(maxSub1.left, maxSub1.right);

	system("pause");
	return 0;
}
3

Co to za bzdury. Takie coś: ArraySolver(rand() % 15 + 5); w konstruktorze nic nie robi. Tworzy obiekt bez nazwy, który znika zaraz po zakończeniu zakresu kontruktora. To samo dzieje się w reszcie kontruktorów.

Albo musisz użyc delegowania konstruktorów (C++11) albo po prostu zrobić całą robotę w każdym z konstruktorów i ewentualnie wydzielić część wspólną do osobnej funkcji. Zacznij też używać listy inicjalizacyjnej w konstruktorze. A jak jesteś ambitny to używaj też std::vector i std::random.

0

Ok, dzięki. Konstruktor, to konstruktor.

1 użytkowników online, w tym zalogowanych: 0, gości: 1