I am getting stuck on print the object Meja1 and Meja2 into class Informasi.
How I can print the object Meja1.print_Meja(); and Meja2.print_Meja();
and please advice me how I can write my code into human readable coding style?
#include <iostream>
#include <string.h>
using namespace std;
class Inventaris {
private:
string Jenis;
string Warna;
string Keadaan;
public:
void setInventaris (string a, string u, string g)
{
Jenis=a;
Warna=u;
Keadaan=g;
}
string getJenis()
{
return Jenis;
}
string getWarna()
{
return Warna;
}
string getKeadaan()
{
return Keadaan;
}
void cetak ()
{
cout<<"Info Inventaris adalah :"<<endl;
cout<<"Jenis : "<<getJenis()<<endl;
cout<<"Warna : "<<getWarna()<<endl;
cout<<"Keadaan : "<<getKeadaan()<<endl;
}
};
class Kursi : public Inventaris {
public:
void print_Kursi(){
hitung++;
cout << "Informasi kursi adalah" <<endl;
cout<<"Jenis : "<<getJenis()<<endl;
cout<<"Warna : "<<getWarna()<<endl;
cout<<"Keadaan : "<<getKeadaan()<<endl;
}
static int hitung;
static getHitung()
{
return hitung;
}
};
class Meja : public Inventaris {
public:
void print_Meja(){
cout << "Informasi Meja adalah" <<endl;
cout<<"Jenis : "<<getJenis()<<endl;
cout<<"Warna : "<<getWarna()<<endl;
cout<<"Keadaan : "<<getKeadaan()<<endl;
hitung_meja++;
}
static int hitung_meja;
static getHitung_meja()
{
return hitung_meja;
}
};
class Informasi : public Meja, public Kursi {
public:
void print_info(){
cout << "Informasi" <<endl;
cout << "Jumlah Meja = " << Meja::getHitung_meja() << endl;
Meja1.print_Meja(); // how I print object Meja1 and Meja2
Meja2.print_Meja();
cout << "Jumlah Kursi = " << Kursi::getHitung() << endl;
}
};
int Kursi::hitung = 0;
int Meja::hitung_meja = 0;
int main() {
Kursi Kursi1;
Kursi1.setInventaris("Kursi goyang","Merah muda", "Bekas");
Kursi1.print_Kursi();
cout << endl;
Kursi Kursi2;
Kursi2.setInventaris("Kursi kakek","reyot", "Bekas");
Kursi2.print_Kursi();
cout << endl;
Meja Meja1;
Meja1.setInventaris("Meja Antik","Coklat tua","Bekas");
Meja1.print_Meja();
cout << endl;
Meja Meja2;
Meja2.setInventaris("Meja Coffee","Hijau Robek","Bekas");
Meja2.print_Meja();
cout << endl;
Informasi info;
info.print_info();
}
I fixed your code and I made Meja1 and Meja2 global declarations so they are accessible by main() and Informasi class.
#include <iostream>
#include <string>
using namespace std;
class Inventaris {
private:
string Jenis;
string Warna;
string Keadaan;
public:
void setInventaris(string a, string u, string g)
{
Jenis = a;
Warna = u;
Keadaan = g;
}
string getJenis()
{
return Jenis;
}
string getWarna()
{
return Warna;
}
string getKeadaan()
{
return Keadaan;
}
void cetak()
{
cout << "Info Inventaris adalah :" << endl;
cout << "Jenis : " << getJenis() << endl;
cout << "Warna : " << getWarna() << endl;
cout << "Keadaan : " << getKeadaan() << endl;
}
};
class Kursi : public Inventaris {
public:
void print_Kursi() {
hitung++;
cout << "Informasi kursi adalah" << endl;
cout << "Jenis : " << getJenis() << endl;
cout << "Warna : " << getWarna() << endl;
cout << "Keadaan : " << getKeadaan() << endl;
}
static int hitung;
static int getHitung() // <--- FIXED!
{
return hitung;
}
};
class Meja : public Inventaris {
public:
void print_Meja() {
cout << "Informasi Meja adalah" << endl;
cout << "Jenis : " << getJenis() << endl;
cout << "Warna : " << getWarna() << endl;
cout << "Keadaan : " << getKeadaan() << endl;
hitung_meja++;
}
static int hitung_meja;
static int getHitung_meja() // <--- FIXED!
{
return hitung_meja;
}
};
Meja Meja1; // <--- Global declaration accessible by main() and Informasi
Meja Meja2; // <--- Global declaration accessible by main() and Informasi
class Informasi : public Meja, public Kursi {
public:
void print_info() {
cout << "Informasi" << endl;
cout << "Jumlah Meja = " << Meja::getHitung_meja() << endl;
Meja1.print_Meja();
Meja2.print_Meja();
cout << "Jumlah Kursi = " << Kursi::getHitung() << endl;
}
};
int Kursi::hitung = 0;
int Meja::hitung_meja = 0;
int main() {
Kursi Kursi1;
Kursi1.setInventaris("Kursi goyang", "Merah muda", "Bekas");
Kursi1.print_Kursi();
cout << endl;
Kursi Kursi2;
Kursi2.setInventaris("Kursi kakek", "reyot", "Bekas");
Kursi2.print_Kursi();
cout << endl;
Meja1.setInventaris("Meja Antik", "Coklat tua", "Bekas");
Meja1.print_Meja();
cout << endl;
Meja2.setInventaris("Meja Coffee", "Hijau Robek", "Bekas");
Meja2.print_Meja();
cout << endl;
Informasi info;
info.print_info();
}
Related
I would Like to construct a class that contains itself but I have to avoid an endless loop. For example I started of my class
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class box {
protected:
int id;
vector<box*> intmega;
int n = 10;
public:
box(box const& autre, int id) : n(autre.n), id(id) {
for (auto& element : autre.get_intmega()) {
intmega.push_back(new box(*element, id + 100));
}
cout << "A new object has seen light" << endl;
}
box(int id) : n(10), id(id) { cout << "Created Box" << endl; }
void ajoute2(box& autre) { intmega.push_back(new box(autre)); }
int size_() const { return intmega.size(); }
int number() const { return n; }
box* get() { return intmega[0]; }
vector<box*> get_intmega() const { return intmega; }
int getId() const { return id; }
~box() {
cout << this << endl;
for (auto element : this->intmega)
delete element;
}
};
void affichel(box const& autre) {
cout << "Box :" << autre.getId() << endl;
cout << "Box :" << &autre << endl;
}
void affiche(box& autre) {
for (auto* element : autre.get_intmega()) {
affichel(*element);
affiche(*element);
cout << endl;
}
}
int main() {
box box1(1);
box box2(2);
box box3(3);
box2.ajoute2(box3);
box1.ajoute2(box2);
box box4(box1, 4);
affiche(box1);
cout << "Box1 Address : " << &box1 << endl;
affiche(box4);
cout << "Box4 Address : " << &box4 << endl;
return 0;
}
Everything works fine but upon calling the destructor disaster.
It deletes all objects but it gets into an endless loop of deleting an object that has already been deleted. Any suggestions help?
I made those slight modifications and now my program works just fine.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class box
{
protected:
vector<box*> intmega;
int n = 10;
public:
box(box const &autre) : n(autre.n)
{
for (auto &element : autre.get_intmega())
{
intmega.push_back(new box(*element));
}
cout << "A new object has seen light" << endl;
cout<<this<<endl;
}
box()
{
cout << "Created Box" << endl;
cout<<this<<endl;
}
void ajoute2(box & autre){
intmega.push_back(new box(autre));
}
int size_() const
{
return intmega.size();
}
int number() const
{
return n;
}
vector<box *> get_intmega() const
{
return intmega;
}
~box()
{
cout<<this<<endl;
for(auto element: this->intmega){
delete element;
}
}
};
void affichel(box const &autre)
{
cout << "Box :" << &autre<< endl;
}
void affiche(box &autre)
{
for (auto *element : autre.get_intmega())
{
affichel(*element);
affiche(*element);
cout << endl;
}
}
int main()
{
box box1;
box box2;
box box3;
box box4;
box3.ajoute2(box4);
box2.ajoute2(box3);
box1.ajoute2(box2);
box box5(box1);
affiche(box1);
cout << "Box1 Address : " << &box1 << endl ;
affiche(box5);
cout << "Box5 Address : " << &box4 << endl ;
return 0;
}
When I tried to convert it the class result can't get the data from class marks even if I made the data variables of marks public I don't know why. I also declared a object of class marks in result and then tried to access it but failed again I am new to coding so don't know all the syntax correctly your help will be of great use
#include <string.h>
#include <iostream>
using namespace std;
class student {
private:
int rl;
char nm[20];
public:
void read();
void display();
};
class marks : public student {
protected:
int s1;
int s2;
int s3;
public:
void getmarks();
void putmarks();
};
class result : public marks {
private:
int t;
float p;
char div[10];
public:
void process();
void printresult();
};
void student::read() {
cout << "enter Roll no and Name " << endl;
cin >> rl >> nm;
}
void student::display() {
cout << "Roll NO:" << rl << endl;
cout << "name : " << nm << endl;
}
void marks ::getmarks() {
cout << "enter three subject marks " << endl;
cin >> s1 >> s2 >> s3;
}
void marks ::putmarks() {
cout << "subject 1:" << s1 << endl;
cout << "subject 2 :" << s2 << endl;
cout << "subject 3:" << s3 << endl;
}
void result::process() {
t = s1 + s2 + s3;
p = t / 3.0;
p >= 60 ? strcpy(div, "first")
: p >= 50 ? strcpy(div, "second")
: strcpy(div, "third");
}
void result::printresult() {
cout << "total = " << t << endl;
cout << "per = " << p << "%" << endl;
cout << "div = " << div << endl;
}
int main(){
result x;
x.read();
x.getmarks();
x.process();
x.display();
x.putmarks();
x.printresult();
}
#include<iostream>
#include<string.h>
using namespace std;
class marks // parent class
{
protected:
int s1;
int s2;
int s3;
public:
void getmarks();
void putmarks();
};
class student : public marks // child class
{
private:
int rl;
char nm[20];
public:
void read();
void display();
};
class result : public marks// child class
{
private:
int t;
float p;
char div[10];
public:
void process();
void printresult();
};
void student::read()
{
cout<<"enter Roll no and Name "<<endl;
cin>>rl>>nm;
}
void student:: display()
{
cout <<"Roll NO:"<<rl<<endl;
cout<<"name : "<<nm<<endl;
}
void marks ::getmarks()
{
cout<<"enter three subject marks "<<endl;
cin>>s1>>s2>>s3;
}
void marks ::putmarks()
{
cout <<"subject 1:"<<s1<<endl;
cout<<"subject 2 :"<<s2<<endl;
cout <<"subject 3:"<<s3<<endl;
}
void result::process()
{
t= s1+s2+s3;
p = t/3.0;
p>=60?strcpy(div,"first"):p>=50?strcpy(div, "second"): strcpy(div,"third");
}
void result::printresult()
{
cout<<"total = "<<t<<endl;
cout<<"per = "<<p<<"%"<<endl;
cout<<"div = "<<div<<endl;
}
int main()
{
result x;
student y;
y.read();
x.getmarks();
x.process();
y.display();
x.putmarks();
x.printresult();
}
I am a first year student of programming, and I need some help.
I have code with public class but I need to change public to private. And it doesn't work for me. Maybe somebody can help me with some suggestions? Here's my working code with public objects, but I need to private. How can I do that?
This is my class's files:
Klientas.h:
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
class Klientas
{
public:
string vardas;
double lesos;
};
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
Klipas.h :
class Klipas
{
public:
string produktas;
string grupe;
double trukme;
double krastine1;
double krastine2;
double plotas;
double klipoSekKaina;
double klipoKaina;
};
My code:
Lab_1.cpp
#include "Klipas.h"
#include "Klientas.h"
using namespace std;
//---------------------------------------------
int main() {
setlocale(LC_ALL, "Lithuanian");
Klipas K[100];
int na;
Klientas kl;
// Iš failo fv įveda duomenis į objektų masyvą K(kiek).
ĮvestiDuomenis("Duomenys.txt", K, na);
SpausdintiDuomenis("Rezultatai.txt", K, na);
}
void ĮvestiDuomenis(string fv, Klipas K[], int & kiek) {
ifstream fd ("Duomenys.txt");
fd >> kiek;
fd.ignore();
for (int i = 0; i < kiek; i++) {
getline(fd, K[i].produktas, ','); fd >> ws;
fd >> K[i].grupe;
fd >> K[i].trukme;
fd >> K[i].krastine1;
fd >> K[i].krastine2;
fd >> K[i].klipoSekKaina;
fd.ignore();
}
fd.close();
// cout << "Programa baigė darbą\n";
}
// Objektų masyvo K(kiek) reikšmes spausdina lentele į failą fv
void SpausdintiDuomenis(string fv, Klipas K[], int kiek) {
ofstream fr("Rezultatai.txt", ios::app);
fr.setf(ios::fixed); fr.setf(ios::left);
cout << "Klipų skaičius: " << kiek << endl;
cout << "Klipų sąrašas:\n";
cout << "----------------------------------------------------\n";
cout << "| Produktas | Grupė | Klipo trukmė(s) | 1 Kraštinė(cm) | 2 Kraštinė(cm) | Klipo sekundės kaina(Eur/s) | \n";
cout << "----------------------------------------------------\n";
for (int i = 0; i < kiek; i++) {
cout << "| " << setw(10) << K[i].produktas << "| " << K[i].grupe
<< setprecision(0) << setw(10) << "| " << K[i].trukme << "| " << setw(15) << K[i].krastine1 << "| " << setw(10) << K[i].krastine2 << "| " << setw(10) << K[i].klipoSekKaina << endl;
}
{
cout << "-------------------------------\n";
cout << "Klipo Kava plotas:" << K[0].krastine1*K[0].krastine2 << " " << "cm2" << endl;
cout << "Klipo Obuolys plotas:" << K[1].krastine1*K[1].krastine2 << " " << "cm2" << endl;
cout << "Klipo Sultys plotas:" << K[2].krastine1*K[2].krastine2 << " " << "cm2" << endl;
cout << "-------------------------------\n";
}
string ilg_trukme; // randame kuris klipas yra ilgiausias
if (K[0].trukme > K[1].trukme) {
ilg_trukme = K[0].produktas;
} else if (K[1].trukme > K[2].trukme) {
ilg_trukme = K[1].produktas;
} else {
ilg_trukme = K[2].produktas;
}
cout << "Ilgiausias klipas: " << ilg_trukme << endl;
cout << "-------------------------------\n";
{
K[0].klipoKaina = K[0].trukme * K[0].klipoSekKaina;
K[1].klipoKaina = K[1].trukme * K[1].klipoSekKaina;
K[2].klipoKaina = K[2].trukme * K[2].klipoSekKaina;
cout << "Klipo Kava Kaina:" << K[0].klipoKaina << " " << "Eur." << endl;
cout << "Klipo Obuolys Kaina:" << K[1].klipoKaina << " " << "Eur." << endl;
cout << "Klipo Sultys Kaina:" << K[2].klipoKaina << " " << "Eur." << endl;
cout << "-------------------------------\n";
}
{
string brangiausias_klipas; //randame kuris klipas brangiausias
double br_kl;
Klientas kl;
if (K[0].klipoKaina > K[1].klipoKaina && K[0].klipoKaina > K[2].klipoKaina ) {
brangiausias_klipas = K[0].produktas;
br_kl = K[0].klipoKaina;
} else if (K[1].klipoKaina > K[2].klipoKaina) {
brangiausias_klipas = K[1].produktas;
br_kl = K[1].klipoKaina;
} else {
brangiausias_klipas = K[2].produktas;
br_kl = K[2].klipoKaina;
}
cout << "Brangiausias klipas yra: " << brangiausias_klipas << endl;
cout << "-------------------------------\n";
cout << "Kiek jūs turite pinigų? " << endl; //kliento turimos pajamos
cin >> kl.lesos ;
cout << "-------------------------------\n";
//Randame kuriuos klipus klientas glaėtų įsigyti su savo pajamom
{
if(kl.lesos < K[0].klipoKaina && kl.lesos < K[1].klipoKaina && kl.lesos < K[2].klipoKaina) {
cout << "Jūs negalite nusipikrti nei vieno klipo " << endl;
} else {
if(kl.lesos >= K[0].klipoKaina) {
cout << "Jūs galite nusipirkti klipą " << K[0].produktas << endl;
}
if (kl.lesos >= K[1].klipoKaina) {
cout << "Jūs galite nusipirkti klipą " << K[1].produktas << endl;
}
if (kl.lesos >= K[2].klipoKaina) {
cout << "Jūs galite nusipirkti klipą " << K[2].produktas << endl;
}
}
}
}
}
Your teacher probably wants you to use getters.
In:
class Klipas
{
public:
string produktas;
string grupe;
double trukme;
double krastine1;
double krastine2;
double plotas;
double klipoSekKaina;
double klipoKaina;
};
You want to have access to all these members, but prevent external changes.
So you can change your code to:
class Klipas
{
public:
string GetProduktas() {return produktas;}
string Getgrupe() {return grupe;}
double Gettrukme() {return trukme;}
double Getkrastine1() {return krastine1;}
double Getkrastine2() {return krastine2;}
double Getplotas() {return plotas;}
double GetklipoSekKaina(){return klipoSekKaina;}
double GetklipoKaina() {return klipoKaina;}
private:
string produktas;
string grupe;
double trukme;
double krastine1;
double krastine2;
double plotas;
double klipoSekKaina;
double klipoKaina;
};
and use those getters instead of the objects themselves in your function:
fd >> K[i].Getgrupe();
fd >> K[i].Gettrukme();
fd >> K[i].Getkrastine1();
fd >> K[i].Getkrastine2();
fd >> K[i].GetklipoKaina();
As for setters go, you can either set your values in the constructor, or implement the same way:
public:
void SetProduktas(string prdkt) {produktas = prdkt;}
You can rewrite your class variables to be private and then use getters and setters to modify them.
class C {
private:
int id;
public:
int get_id() { return this->id; }
void set_id(int newId) { this->id = newId; }
};
Or you can make private class inside of another class
class A {
private:
class D {};
};
I've been using this code for my TicTacToe game but I want to make some changes:
first I want to introduce the name of the players, and when one of them wins, it appears on the message.
second, I want to introduce a ranking table of records, winning games and tied ones
third I want the table to be static, doesn't change in every move.
forth I want the table to have always the numbers in the square that each of them represent, and when someone chooses that position, it replaces the number for the pieace, X or O.
Now I'll post the code above of every file:
Player.h
#ifndef PLAYER_H
#define PLAYER_H
class Board;
class Player
{
public:
Player();
char GetPiece() const;
void MakeMove(Board& aBoard) const;
private:
static const int NUM_PIECES = 2;
static const char PIECES[NUM_PIECES];
static int current;
char m_Piece;
};
#endif
Player.cpp
#include "player.h"
#include "board.h"
#include <iostream>
using namespace std;
const char Player::PIECES[NUM_PIECES] = {'X', 'O'};
int Player::current = 0;
Player::Player()
{
m_Piece = PIECES[current];
current = (current + 1) % NUM_PIECES;
}
char Player::GetPiece() const
{
return m_Piece;
}
void Player::MakeMove(Board& aBoard) const
{
int move;
do
{
cout << "Player " << GetPiece();
cout << ", where would you like to move? (0-8): ";
cin >> move;
} while (!aBoard.IsLegalMove(move));
aBoard.ReceiveMove(GetPiece(), move);
}
Board.h
#ifndef BOARD_H
#define BOARD_H
class Board
{
public:
Board();
bool IsFull() const;
bool IsLegalMove(int move) const;
bool IsWinner(char piece) const;
void Display() const;
void Reset();
void ReceiveMove(char piece, int move);
static const int NUM_SQUARES = 9;
static const char EMPTY = ' ';
private:
static const int NUM_COMBOS = 8;
static const int NUM_IN_COMBO = 3;
static const int WINNING_COMBOS[NUM_COMBOS]
[NUM_IN_COMBO];
char m_Squares[NUM_SQUARES];
};
#endif
Board.cpp
#include "board.h"
#include <iostream>
using namespace std;
const int Board::WINNING_COMBOS[NUM_COMBOS]
[NUM_IN_COMBO] = { {0, 1, 2},{3, 4, 5},{6, 7, 8},{0, 3, 6},{1, 4, 7},{2, 5, 8},{0, 4, 8}, {2, 4, 6} };
Board::Board()
{
Reset();
}
bool Board::IsFull() const
{
bool full = true;
int i = 0;
while (full && i < NUM_SQUARES)
{
if (m_Squares[i] == EMPTY)
{
full = false;
}
++i;
}
return full;
}
bool Board::IsLegalMove(int move) const
{
return (move >= 0 && move < NUM_SQUARES && m_Squares[move] == EMPTY);
}
bool Board::IsWinner(char piece) const
{
bool winner = false;
int i = 0;
while (!winner && i < NUM_COMBOS)
{
int piecesInCombo = 0;
for (int j = 0; j < NUM_IN_COMBO; ++j)
{
if (m_Squares[WINNING_COMBOS[i][j]] == piece)
{
++piecesInCombo;
}
}
if (piecesInCombo == NUM_IN_COMBO)
{
winner = true;
}
++i;
}
return winner;
}
void Board::Display() const
{
cout << endl << "\t" << m_Squares[0] << " | " << m_Squares[1];
cout << " | " << m_Squares[2];
cout << endl << "\t" << "---------";
cout << endl << "\t" << m_Squares[3] << " | " << m_Squares[4];
cout << " | " << m_Squares[5];
cout << endl << "\t" << "---------";
cout << endl << "\t" << m_Squares[6] << " | " << m_Squares[7];
cout << " | " << m_Squares[8];
cout << endl << endl;
}
void Board::Reset()
{
for (int i=0; i<NUM_SQUARES; ++i)
{
m_Squares[i] = EMPTY;
}
}
void Board::ReceiveMove(char piece, int move)
{
m_Squares[move] = piece;
}
Game.h
#ifndef GAME_H
#define GAME_H
#include "board.h"
#include "player.h"
class Game
{
public:
Game();
bool IsPlaying() const;
bool IsTie() const;
void DisplayInstructions() const;
void NextPlayer();
void AnnounceWinner() const;
void Play();
private:
static const int NUM_PLAYERS = 2;
static const int FIRST = 0;
static const int SECOND = 1;
Board m_Board;
Player m_Players[NUM_PLAYERS];
int m_Current;
};
#endif
Game.cpp
#include "game.h"
#include <iostream>
using namespace std;
Game::Game():
m_Current(FIRST)
{}
bool Game::IsPlaying() const
{
return ( !m_Board.IsFull() &&!m_Board.IsWinner(m_Players[FIRST].GetPiece()) &&
!m_Board.IsWinner(m_Players[SECOND].GetPiece()) );
}
bool Game::IsTie() const
{
return ( m_Board.IsFull() &&!m_Board.IsWinner(m_Players[FIRST].GetPiece()) &&
!m_Board.IsWinner(m_Players[SECOND].GetPiece()) );
}
void Game::DisplayInstructions() const
{
cout << "\tWelcome to the ultimate intellectual
showdown: Tic-Tac-Toe.";
cout << endl << endl;
cout << "Make your move by entering a number,
0 - 8. The number" << endl;
cout << "corresponds with board position, as
illustrated:" << endl << endl;
cout << endl << "\t" << "0 | 1 | 2";
cout << endl << "\t" << "---------";
cout << endl << "\t" << "3 | 4 | 5";
cout << endl << "\t" << "---------";
cout << endl << "\t" << "6 | 7 | 8";
cout << endl << endl << "Prepare yourself. The
battle is about to begin.";
cout << endl << endl;
}
void Game::NextPlayer()
{
m_Current = (m_Current + 1) % NUM_PLAYERS;
}
void Game::AnnounceWinner() const
{
cout << "The raging battle has come to a fi nal end.";
cout << endl;
if (IsTie())
{
cout << "Sadly, no player emerged victorious.";
cout << endl;
}
else
{
cout << "The winner of this climatic ";
cout << "confrontation is Player ";
if (m_Board.IsWinner(m_Players[FIRST].
GetPiece()))
{
cout << m_Players[FIRST].GetPiece() << "!";
cout << endl;
}
else
{
cout << m_Players[SECOND].GetPiece() << "!";
cout << endl;
}
}
}
void Game::Play()
{
m_Current = FIRST;
m_Board.Reset();
while (IsPlaying())
{
m_Board.Display();
m_Players[m_Current].MakeMove(m_Board);
NextPlayer();
}
m_Board.Display();
AnnounceWinner();
}
main.cpp
#include "game.h"
#include <iostream>
using namespace std;
int main()
{
Game ticTacToe;
ticTacToe.DisplayInstructions();
char again;
do
{
ticTacToe.Play();
cout << endl << "Play again? (y/n): ";
cin >> again;
} while (again != 'n');
return 0;
}
I'm not going to write code for you, but I'm slightly bored at the moment so I will structure it somewhat so you have an idea.
You need to store the name per player, and some way to retrieve it for the winning playerwhen the game is finished.
You need to keep track of scores, store between sessions which means file i/o.
I don't understand what you want with 3 or 4.
Mi version en español y ademas lo mejoré un poquito
main.cpp
#include "Arbitro.h"
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
system("color 09");
Arbitro Triqui;
Triqui.mostrarInstrucciones();
string continuar;
cout<<"\t\t\t\t presione cualquier tecla para continuar";
continuar = (char)getch();
system("cls");
char deNuevo;
do
{
Triqui.jugar();
cout << endl << "\t\t\tQuieres jugar otra vez? (s/n): ";
cin >> deNuevo;
system ("cls");
} while (deNuevo != 'n');
cout << endl;
cout << "\t\t\t\t/////////////////////////////////////////////////////\n";
cout << "\t\t\t\t// Autor: //\n";
cout << "\t\t\t\t// //\n";
cout << "\t\t\t\t// Camilo Andres Granda Codigo: 201759710 //\n";
cout << "\t\t\t\t// //\n";
cout << "\t\t\t\t/////////////////////////////////////////////////////\n";
cout << endl;
return 0;
}
Arbitro.h
#ifndef ARBITRO_H
#define ARBITRO_H
#include "Tablero.h"
#include "Jugador.h"
class Arbitro
{
public:
Arbitro();
bool enJuego() const;
bool empate() const;
void mostrarInstrucciones() const;
void siguienteJugador();
void anunciarGanador() const;
void jugar();
private:
static const int numero_de_jugadores = 2;
static const int primero = 0;
static const int segundo = 1;
Tablero m_Tablero;
Jugador m_Jugadores[numero_de_jugadores];
int m_Actual;
};
#endif
Arbitro.cpp
#include "Arbitro.h"
#include <iostream>
using namespace std;
Arbitro::Arbitro():
m_Actual(primero)
{}
bool Arbitro::enJuego() const
{
return ( !m_Tablero.estaLleno()
&&!m_Tablero.ganador(m_Jugadores[primero].getPieza()) &&
!m_Tablero.ganador(m_Jugadores[segundo].getPieza()) );
}
bool Arbitro::empate() const
{
return ( m_Tablero.estaLleno()
&&!m_Tablero.ganador(m_Jugadores[primero].getPieza()) &&
!m_Tablero.ganador(m_Jugadores[segundo].getPieza()) );
}
void Arbitro::mostrarInstrucciones() const
{
cout << "\t\t\t
///////////////////////////////////////////////////////\n";
cout << "\t\t\t // Bienvenidos
//\n";
cout << "\t\t\t
///////////////////////////////////////////////////////\n";
cout << endl << endl;
cout << "\t\t\tHaga su movimiento ingresando un numero, [1 - 9]. El numero"
<< endl;
cout << "\t\t\tcorresponde con la posicion de la tabla, como se ilustra:" <<
endl << endl;
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 1 | 2 | 3 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 4 | 5 | 6 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 7 | 8 | 9 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << endl << "\t\t\t\tPreparate. La partida esta a punto de
comenzar.";
cout << endl << endl;
}
void Arbitro::siguienteJugador()
{
m_Actual = (m_Actual + 1) % numero_de_jugadores;
}
void Arbitro::anunciarGanador() const
{
if (empate())
{
cout << "\t\t\tEmpate, ningun jugador gano.";
cout << endl;
}
else
{
cout << "\t\t\tEl ganador de esta partida es el jugador ";
if (m_Tablero.ganador(m_Jugadores[primero].
getPieza()))
{
cout << m_Jugadores[primero].getPieza() << "!";
cout << endl;
}
else
{
cout << m_Jugadores[segundo].getPieza() << "!";
cout << endl;
}
}
}
void Arbitro::jugar()
{
m_Actual = primero;
m_Tablero.reiniciarTablero();
while (enJuego())
{
m_Tablero.mostrarTablero();
m_Jugadores[m_Actual].hacerMovimiento(m_Tablero);
siguienteJugador();
}
m_Tablero.mostrarTablero();
anunciarGanador();
}
Jugador.h
#ifndef JUGADOR_H
#define JUGADOR_H
#include <iostream>
#include <string> // string, stoi
#include <cctype> // isdigit
#include <cstdlib> // atoi
class Tablero;
class Jugador
{
public:
Jugador();
char getPieza() const;
void hacerMovimiento(Tablero& unTablero) const;
private:
static const int numero_de_fichas = 2;
static const char fichas[numero_de_fichas];
static int actual;
char m_Ficha;
};
#endif
Jugador.cpp
#include "Jugador.h"
#include "Tablero.h"
#include <iostream>
using namespace std;
const char Jugador::fichas[numero_de_fichas] = {'N', 'B'};
int Jugador::actual = 0;
Jugador::Jugador()
{
m_Ficha = fichas[actual];
actual = (actual + 1) % numero_de_fichas;
}
char Jugador::getPieza() const
{
return m_Ficha;
}
void Jugador::hacerMovimiento(Tablero& unTablero) const
{
string linea;
int move;
do
{
cout << "\t\t\tJugador " << getPieza() << ", Donde te gustaria hacer el movimiento? [1 - 9]: ";
cin >> linea;
if (unTablero.esNumerico(linea)) {
move = atoi(linea.c_str());
} else {
cout << "\n\t\t\t\t\tError!, ingrese valor valido\n\n";
move=0;
}
} while (!unTablero.movimientoValido(move));
unTablero.recibirMovimiento(getPieza(), move);
}
Tablero.h
#ifndef TABLERO_H
#define TABLERO_H
#include <iostream>
#include <string> // string, stoi
using namespace std;
class Tablero
{
public:
Tablero();
bool esNumerico(string linea);
bool estaLleno() const;
bool movimientoValido(int move) const;
bool ganador(char ficha) const;
void mostrarTablero() const;
void reiniciarTablero();
void recibirMovimiento(char pieza, int mover);
static const int numero_de_cuadros = 10;
static const char vacio = ' ';
private:
static const int numero_de_combos = 8;
static const int numero_en_combo = 3;
string linea;
static const int combos_ganadores[numero_de_combos] [numero_en_combo];
char m_Cuadrados[numero_de_cuadros];
};
#endif
Tablero.cpp
#include "Tablero.h"
#include <iostream>
using namespace std;
const int Tablero::combos_ganadores[numero_de_combos]
[numero_en_combo] = { {1, 2, 3},{4, 5, 6},{7, 8, 9},{1, 4, 7},{2, 5, 8},{3, 6, 9},{1, 5, 9}, {3, 5, 7} };
Tablero::Tablero()
{
reiniciarTablero();
}
bool Tablero::estaLleno() const
{
bool lleno = true;
int i = 1;
while (lleno && i < numero_de_cuadros)
{
if (m_Cuadrados[i] == vacio)
{
lleno = false;
}
++i;
}
return lleno;
}
bool Tablero::movimientoValido(int mover) const
{
return (mover >= 1 && mover < numero_de_cuadros && m_Cuadrados[mover] ==
vacio);
}
bool Tablero::ganador(char ficha) const
{
bool ganador = false;
int i = 0;
while (!ganador && i < numero_de_combos)
{
int fichasEnCombo = 0;
for (int j = 0; j < numero_en_combo; ++j)
{
if (m_Cuadrados[combos_ganadores[i][j]] == ficha)
{
++fichasEnCombo;
}
}
if (fichasEnCombo == numero_en_combo)
{
ganador = true;
}
++i;
}
return ganador;
}
void Tablero::mostrarTablero() const
{
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[1] << " | " << m_Cuadrados[2]; cout << " | " << m_Cuadrados[3]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[4] << " | " << m_Cuadrados[5]; cout << " | " << m_Cuadrados[6]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[7] << " | " << m_Cuadrados[8]; cout << " | " << m_Cuadrados[9]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << endl;
}
void Tablero::reiniciarTablero()
{
for (int i=0; i<numero_de_cuadros; ++i)
{
m_Cuadrados[i] = vacio;
}
}
void Tablero::recibirMovimiento(char pieza, int mover)
{
m_Cuadrados[mover] = pieza;
}
bool Tablero::esNumerico(string linea)
{
bool b = true;
int longitud = linea.size();
if (longitud == 0) { // Cuando el usuario pulsa ENTER
b = false;
} else if (longitud == 1 && !isdigit(linea[0])) {
b = false;
} else {
int i;
if (linea[0] == '+' || linea[0] == '-')
i = 1;
else
i = 0;
while (i < longitud) {
if (!isdigit(linea[i])) {
b = false;
break;
}
i++;
}
}
return b;
}
I am trying to create a base class which is a template class and accepts, as a templace, some class. This base class in the parent class of two other classes which are themselves the parents of the final class. Thus, I have the traditional diamond problem in c++ with the addition that the root base class is a template class. Using virtual inheritance here does not quite do the trick.
Edit: Included some code (and corrected typos)
#include<iostream>
#include<string>
using namespace std;
template<class TemplateT>
class MainMaster {
protected:
std::string name;
int number;
TemplateT variableProp;
public:
explicit MainMaster(std::string, int);
void setName(std::string);
std::string getName();
void printName();
void setNumber(int);
int getNumber();
void printNumber();
void printMasterProperties(std::string);
void setVarProp(TemplateT);
TemplateT getVarProp();
};
template<class TemplateT>
MainMaster<TemplateT>::MainMaster(std::string nameIn, int numIn){
setName(nameIn);
setNumber(numIn);
}
template<class TemplateT>
void MainMaster<TemplateT>::setName(std::string nameIn){ name = nameIn; }
template<class TemplateT>
std::string MainMaster<TemplateT>::getName(){ return name; }
template<class TemplateT>
void MainMaster<TemplateT>::printName(){ cout << "Master's name is " << name << endl; }
template<class TemplateT>
void MainMaster<TemplateT>::setNumber(int numIn){ number = numIn; }
template<class TemplateT>
int MainMaster<TemplateT>::getNumber(){ return number; }
template<class TemplateT>
void MainMaster<TemplateT>::printNumber(){ cout << name << "'s number is " << number << endl; }
template<class TemplateT>
void MainMaster<TemplateT>::printMasterProperties(std::string pre = ""){
cout << pre << "Master Properties" << endl
<< pre << "-Number: " << number << endl;
}
class ChildOne: public virtual MainMaster<std::string>{
protected:
std::string propOne;
public:
// using MainMaster::MainMaster;
ChildOne(std::string nameIn, int numIn, std::string p1);
void printName();
void setPropOne(std::string);
std::string getPropOne();
void printOnesProps(std::string);
};
ChildOne::ChildOne(std::string nameIn, int numIn, std::string p1): MainMaster<std::string>(nameIn,numIn){
setPropOne(p1);
}
void ChildOne::printName(){ cout << "ChildOne's name is " << name << endl; }
void ChildOne::setPropOne(std::string propIn){ propOne = propIn; }
std::string ChildOne::getPropOne(){ return propOne; }
void ChildOne::printOnesProps(std::string pre = ""){
printMasterProperties("-");
cout << pre << "One Properties" << endl
<< pre << "-PropOne: " << propOne << endl;
}
class ChildTwo: public virtual MainMaster<int>{
protected:
std::string propTwo;
public:
ChildTwo(std::string nameIn, int numIn, std::string p2);
void printName();
void setPropTwo(std::string);
std::string getPropTwo();
void printTwosProps(std::string);
};
ChildTwo::ChildTwo(std::string nameIn, int numIn, std::string p2): MainMaster<int>(nameIn,numIn){
setPropTwo(p2);
}
void ChildTwo::printName(){
cout << "ChidTwo's name is " << name << endl;
}
void ChildTwo::setPropTwo(std::string propIn){ propTwo = propIn; }
std::string ChildTwo::getPropTwo(){ return propTwo; }
void ChildTwo::printTwosProps(std::string pre = ""){
printMasterProperties("-");
cout << pre << "Two Properties" << endl
<< pre << "-PropTwo: " << propTwo << endl;
}
class FinalChild: public ChildOne, public ChildTwo{
protected:
double finalProp;
public:
FinalChild(std::string nameIn, int num, std::string prop1 ,std::string prop2, double pFinal);
void printFinalProps(std::string);
};
FinalChild::FinalChild(std::string nameIn, int num, std::string prop1 ,std::string prop2, double pFinal):
ChildOne(nameIn, num, prop1),
ChildTwo(nameIn, num, prop2),
MainMaster(nameIn, num){
finalProp = pFinal;
}
void FinalChild::printFinalProps(std::string pre = ""){
printMasterProperties("-");
cout << pre << name << "'s Final Properties" << endl;
cout << pre << "-Number: " << number << endl;
cout << pre << "-PropOne: " << propOne << endl;
cout << pre << "-PropTwo: " << propTwo << endl;
cout << pre << "-finalProp " << finalProp << endl;
}
int main () {
MainMaster<char> master("Master", 0);
ChildOne child1("Child1",1,"P1One");
ChildTwo child2("Child2",2,"P2Two");
FinalChild finalC("FinalChild", 3, "P1Final", "P2Final", 3.0);
master.printMasterProperties();
child1.printOnesProps();
child2.printTwosProps();
finalC.printFinalProps();
}