Cześć,
Niedawno zacząłem uczyć się programowania obiektowego, jestem na etapie nauki konstruktorów i destruktorów. Chcę zrobić klasę Stos z kilkoma podstawowymi metodami, dwoma konstruktorami i destruktorem. Według zaleceń treści zadania jeden konstruktor ma mieć jeden parametr, a drugi jest bezparametrowy tzw. konstruktor domyślny. I właśnie problem tkwi w tych konstruktorach, program nie chce działać z konstruktorami. Za wyjaśnienie tego zjawiska BARDZO DZIĘKUJĘ! :)
Tutaj main:
#include<iostream>
#include "Stos.h"
using namespace std;
int main()
{
Stos stos_1;
int wybor;
do
{
stos_1.wyswietl();
cout << "MENU GLOWNE STOSU:" << endl;
cout << "------------------------------------------" << endl;
cout << "1. PUSH (dodaje element na szczyt stosu) " << endl;
cout << "2. POP (usuwa element ze szczytu stosu) " << endl;
cout << "3. TOP (pokazuje wierzcholek) " << endl;
cout << "4. EMPTY (czy stos jest pusty?) " << endl;
cout << "5. Zakonczenie programu " << endl;
cout << "Wybor: ";
cin >> wybor;
switch (wybor)
{
case 1:
stos_1.push(5);
break;
case 2:
stos_1.pop();
break;
case 3:
stos_1.top();
break;
case 4:
stos_1.empty();
break;
}
} while (wybor != 5);
system("PAUSE");
return 0;
}
Tutaj Stos.h
#pragma once
#include<iostream>
using namespace std;
class Stos
{public:
int indeks;
int size;
int* dane = new int[size];
public:
Stos();
Stos(int rozmiar=5);
~Stos();
void wyswietl(); // Wyswietla Menu
void push(int liczba); //Dokłada liczbę na stos
void top(); // Pokazuje liczbę na szczycie
void pop(); // Usuwa liczbe ze stosu
bool empty(); // Sprawdza czy stos jest pusty
};
Stos.cpp
#include "Stos.h"
#include<iostream>
#include <windows.h>
#include <cstdlib>
#include <ctime>
using namespace std;
Stos::Stos()
{
indeks = 0;
size = 10;
dane = new int[10];
cout << endl << "Wywolano konstruktor domyslny" << endl << this << endl;
}
Stos::Stos(int rozmiar)
{
indeks = 0;
size= rozmiar;
dane = new int[rozmiar];
cout << "Wywolano konstruktor parametrowy" << endl << this << endl;
}
Stos::~Stos()
{
delete[] dane;
cout << "Destruktor" << endl;
}
void Stos::wyswietl()
{
system("CLS");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
}
void Stos::push(int liczba)
{
if (indeks >= (size - 1))
{
cout << "Stos pelny!";
Sleep(1000);
}
else
{
cout << endl << "Dodawanie liczby";
indeks = indeks + 1;
dane[indeks] = liczba;
}
}
void Stos::top()
{
cout << endl << "TOP- element na wierzchu " << dane[indeks];
Sleep(2000);
}
void Stos::pop()
{
if (indeks >= 1)
{
cout << endl << "POP - nastapi usuniecie ze stosu liczby: " << dane[indeks];
Sleep(2000);
indeks = indeks - 1;
}
else
{
cout << "Stos pusty!";
Sleep(1000);
}
}
bool Stos::empty()
{
if (indeks == 0) { return true; }
else { return false; }
}