I am creating a UNO game that transfers Card objects from a deck to a hand. Each player has a hand which consists of 7 random cards. The code below shows me attempting to create a player and storing the player into an array that can alter the order of turns and such. I initialized my array by Player* playerArray
#pragma once
#include "Player.h"
#include "DevTest.h"
#include <string>
class Game
{
private:
int amountOfPlayers;
//std::vector<Player> playerArray;
Player* playerArray; //in charge of the order of turns etc
public:
Game();
void createPlayerArray();
void menu();
~Game();
};
And this is where I implement my array
#include "Game.h"
DevTest devtest;
extern Player player;
extern Deck deck;
Game::Game()
{
}
void Game::createPlayerArray()
{
std::string userName;
std::cout << "Please enter the amount of players: ";
std::cin >> amountOfPlayers;
if (amountOfPlayers < 2 || amountOfPlayers>10)
{
if (amountOfPlayers < 2)
{
std::cout << "Sorry! Not enough players." << std::endl;
}
if (amountOfPlayers > 10)
{
std::cout << "Sorry! Too many players." << std::endl;
}
}
else
{
playerArray = new Player[amountOfPlayers];
std::cout << "Please enter the names of each player." << std::endl;
for (int i = 0; i < amountOfPlayers; i++)
{
//Player* playerArray[i] = new Player;
std::cout << "Player " << i+1 << ": ";
std::cin.ignore();
std::getline(std::cin, userName);
playerArray[i].setUserName(userName);
for (int i = 0; i < player.getHANDSIZE(); i++)
{
deck.dealCard();
}
player.printHand();
}
}
return;
}
void Game::menu()
{
int choice;
std::cout << "UNO" << std::endl;
std::cout << "1. Play Game" << std::endl;
std::cout << "2. Read Rules" << std::endl;
std::cout << "3. Developer Testing" << std::endl;
std::cout << "4. Quit" << std::endl;
do
{
std::cin >> choice;
switch (choice)
{
case 1:
std::cout << "Play Game" << std::endl;
break;
case 2:
std::cout << "Read Rules" << std::endl;
break;
case 3:
std::cout << "Developer Testing" << std::endl;
devtest.testMenu();
break;
case 4:
exit(0);
break;
default:
std::cout << "Invalid choice. Please choose again." << std::endl;
}
//clear screen
} while (choice < 1 || choice >4);
}
Game::~Game()
{
}
PLAYER
#pragma once
#include "Deck.h"
#include <iostream>
class Player
{
private:
int length;
std::string username; //can indicate whos turn / wins
static const int HANDSIZE = 7;
Card* hand;
public:
Player();
void pushHand(Card deck);
void popHand();
void printHand();
int getHANDSIZE();
std::string getUserName();
void setUserName(std::string name);
~Player();
};
PLAYER.CPP
#include "Player.h"
#include "Card.h"
extern Deck deck;
//extern Game game;
Player::Player()
{
length = 0;
hand = new Card[HANDSIZE];
//game.createPlayerArray();
//new player?
}
void Player::pushHand(Card deck)
{
//push deck object into hand
hand[length] = deck;
length++;
}
void Player::printHand()
{
for (int i = 0; i < length; i++)
{
std::cout << "Length: " << i << std::endl;
std::cout << "Value: " << hand[i].value << std::endl;
std::cout << "Color: ";
deck.toString(hand[i].color);
}
}
int Player::getHANDSIZE()
{
return HANDSIZE;
}
std::string Player::getUserName()
{
return username;
}
void Player::setUserName(std::string name)
{
username = name;
}
Player::~Player()
{
}
My issue is, my array has a length of 0 even though I create the array with `playerArray = new Player[amountOfPlayers];`
which to my understanding creates an array of player objects with a given size. My question is, how do I create an array of Player objects correctly since either this declaration is flawed or my logic somewhere else is flawed.
Also, I cannot use vectors due to the instructor's instructions.
Using breakpoints and Debug>Windows>Locals, I can see that my player array has a length of 0 instead of 2. I'm not sure as to what I'm doing incorrectly and a few pointers/tips would be very appreciated.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So, I am learning about classes in C++, I created two classes, one for a University that contains a list of class Students, i managed to create students, and introduce some values to the classes, but now i want to sort the class students by student number, i tryed using the sort function, but im not succeeding. I will leave my code bellow, please give some good tips and advises, so I can improve my code. thanks
main.css
#include <iostream>
#include "university.h"
#include "students.h"
using namespace std;
int main() {
university univ = university();
return 0;
}
university.h
#pragma once
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include "students.h"
using namespace std;
class university
{
private:
list<students> lstudents;
list<students>::iterator itstudents;
public:
university();
void setStudents(list<students> lstudents);
void registerStudent();
void list();
void average();
//void sortstudents();
};
university.cpp
#include "university.h"
using namespace std;
university::university() { //constructor
string resp = "s";
int op;
bool out = true;
cout << "Enter Students:" << endl;
while (resp != "n")
{
this->registerStudent();
cout << "Continue inserting? (s/n)" << endl;
cin >> out;
cin.ignore();
}
while (out)
{
cout << "What you Want to do? (1- List Students 2- Sudent Average 3- Sort Students by Number 4- Leave)" << endl;
cin >> op;
switch (op)
{
case 1:
this->list();
break;
case 2:
this->average();
break;
/*case 3:
this->sortStudents();
break;*/
case 4:
out = false;
break;
};
}
}
void university::setStudents(list<students> lstudents) {
this->lstudents = lstudents;
}
void university::registerStudent()
{
lstudents.push_back(students());
}
void university::list()
{
int sum = 0;
cout << "------------------------- LIST STUDENTS -------------------------------\n\n";
cout << left << setw(11) << "Number"
<< left << setw(30) << "Name"
<< left << setw(30) << "Course"
<< left << setw(10) << "Average";
cout << "\n";
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
(*itstudents).list();
++sum;
}
//cout << "Total de pacientes:" << somatorio << endl;
//somatorio = 0;
}
void university::average()
{
int sum = 0;
double average = 0;
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
average += (*itstudents).getaverage();
++sum;
}
cout << "Average:" << average / sum << endl;
}
//void university::sortstudents() {
// sort(lstudents.begin(), lstudents.end(), &students::compare);
//}
students.h
as you can see the commented code is my attempts on sorting the class student my number
#pragma once
#include <iomanip>
#include <algorithm>
#include <list>
#include "university.h"
using namespace std;
class students {
private:
std::string name;
std::string course;
int number;
double average;
public:
//friend bool operator<(estudantes& left,estudantes& right) { return left.matricula < right.matricula; };
students();
void list();
double getaverage();
int getnumber();
//bool compare(estudantes a, estudantes b);
};
students.cpp
#include "students.h"
students::students() {
cout << "Name: ";
getline(cin, name);
cout << "Course: ";
getline(cin, course);
cout << "Number: ";
cin >> this->number;
cout << "Average: ";
cin >> this->average;
}
void students::list() {
cout << left << setw(11) << number;
cout << left << setw(30) << name;
cout << left << setw(30) << course;
cout << left << setw(10) << average << endl;
}
double students::getaverage() {
return average;
}
int students::getnumber() {
return number;
}
//bool estudantes::compare(student a, student b) {
//
// if (a.number < b.number)
// return 1;
// else
// return 0;
//}
Made it selfcontained and fixed. I'll post and then aexplain as surely people will have closed the question too soon:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
#include <string>
class students {
private:
std::string name;
std::string course;
int number;
double average;
public:
// friend bool operator<(students& left,students& right) { return
// left.matricula < right.matricula; };
students();
void list();
double getaverage();
int getnumber();
static bool compare(students const& a, students const& b);
};
students::students()
{
std::cout << "Name: "; getline(std::cin, name);
std::cout << "Course: "; getline(std::cin, course);
std::cout << "Number: "; std::cin >> this->number;
std::cout << "Average: "; std::cin >> this->average;
}
void students::list() {
std::cout << std::left << std::setw(11) << number;
std::cout << std::left << std::setw(30) << name;
std::cout << std::left << std::setw(30) << course;
std::cout << std::left << std::setw(10) << average << std::endl;
}
double students::getaverage() {
return average;
}
int students::getnumber() {
return number;
}
bool students::compare(students const& a, students const& b) {
return a.number > b.number;
}
class university {
private:
std::list<students> lstudents;
std::list<students>::iterator itstudents;
public:
university();
void setStudents(std::list<students> lstudents);
void registerStudent();
void list();
void average();
void sortStudents();
};
university::university() // constructor
{
std::string resp = "s";
int op;
bool out = true;
std::cout << "Enter Students:" << std::endl;
while (resp != "n") {
this->registerStudent();
std::cout << "Continue inserting? (s/n)" << std::endl;
std::cin >> out;
std::cin.ignore();
}
while (out) {
std::cout << "What you Want to do? (1- List Students 2- Sudent Average "
"3- Sort Students by Number 4- Leave)"
<< std::endl;
std::cin >> op;
switch (op) {
case 1: this->list(); break;
case 2:
this->average();
break;
case 3: this->sortStudents(); break;
case 4: out = false; break;
};
}
}
void university::setStudents(std::list<students> lstudents) {
this->lstudents = lstudents;
}
void university::registerStudent()
{
lstudents.push_back(students());
}
void university::list()
{
int sum = 0;
std::cout << "------------------------- LIST STUDENTS -------------------------------\n\n";
std::cout << std::left << std::setw(11) << "Number"
<< std::left << std::setw(30) << "Name"
<< std::left << std::setw(30) << "Course"
<< std::left << std::setw(10) << "Average";
std::cout << "\n";
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
(*itstudents).list();
++sum;
}
//std::cout << "Total de pacientes:" << somatorio << std::endl;
//somatorio = 0;
}
void university::average()
{
int sum = 0;
double average = 0;
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
average += (*itstudents).getaverage();
++sum;
}
std::cout << "Average:" << average / sum << std::endl;
}
void university::sortStudents() {
lstudents.sort(&students::compare);
}
int main() {
university univ = university();
return 0;
}
Explanation
There were a number of issues.
students::compare was a non-static member function, meaning it can only be called on an instance of student. To have a 2-argument sort predicate as required, simply making it static can work
The implementation could be much more idiomatic:
bool students::compare(students const& a, students const& b) {
return a.number > b.number;
}
That avoids the C-ism of using 1 as if it were true, and the useless if/else
You used std::sort but it requires random access iterators. std::list doesn't provide that. For that reason std::list::sort exists:
void university::sortStudents() {
lstudents.sort(&students::compare);
}
Among many other style issues:
don't using namespace std;
don't do side-effects in constructors?
error-check IO
avoid division by zero (e.g. in average()
I've made a text based game for my project in VSCode (gcc). The main problem is that VSCode gives me strange output while Clion (visual-c++) gives me the right one.
For example in VSCode I get negative numbers as my damage while in Clion I get the right ones.
I hope the code that I provided will help you to find the reason to this strange behaviour
I want to know how to fix this problem and how to avoid it in the near future. Thank you in advance
Main.cpp
#include <iostream>
#include <vector>
#include <ctime>
#include <string>
#include <algorithm>
#include "mob.h"
using namespace std;
int main()
{
//Random seed
srand(time(nullptr));
//Player Initialization
//Mobs Initialization
mob Skeleton{rand()%51+50, rand()%21+30, rand()%11, "Skeleton", rand()%11+10};
mob Zombie{rand()%101+100, rand()%11+10, rand()%21, "Zombie", rand()%11};
mob Spider{rand()%21+30, rand()%11+20, rand()%11, "Spider", rand()%21+50};
mob Creeper{rand()%16+5, rand()%51+50, 0, "Creeper", rand()%6};
//Array of mobs
vector <mob> mobs;
mobs.push_back(Skeleton);
mobs.push_back(Zombie);
mobs.push_back(Spider);
mobs.push_back(Creeper);
//Fight
int CurrentAttack = 0, n;
while (1 < mobs.size())
{
//Mobs order output
cout << endl << mobs[0].name << endl;
cout << "Choose who to attack:" << endl;
tryAgain: //In case if user typed wrong number
for (int q = 1; q < mobs.size(); q++)
{
cout << q << " - " << mobs[q].name << endl;
}
//Choose who to attack
cin >> n;
switch (n)
{
case 1:
{
mobs[0].Attack(CurrentAttack);
mobs[1].TakeHit(CurrentAttack);
mobs[1].Return();
break;
}
case 2:
{
if (n > mobs.size()-1)
{ printf("This enemy is already dead");
goto tryAgain;
}
mobs[0].Attack(CurrentAttack);
mobs[2].TakeHit(CurrentAttack);
mobs[2].Return();
break;
}
case 3:
{
if (n > mobs.size()-1)
{
cout << "This enemy is already dead" << endl;
goto tryAgain;
}
mobs[0].Attack(CurrentAttack);
mobs[3].TakeHit(CurrentAttack);
mobs[3].Return();
break;
}
default:
goto tryAgain;
}
if (mobs[n].Health() == 0)
{
//Remove dead mob
rotate(mobs.begin(),mobs.begin()+n+1,mobs.end());
mobs.pop_back();
}
else
{
//Rotate Vector for different mob to attack
rotate(mobs.begin(),mobs.begin()+1,mobs.end());
}
}
cout << "⣿⣿⣿⣿⡿⠟⠛⠛⠛⠛⠉⠉⠙⠛⠛⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠟" << endl << "⣿⣿⣯⣥⣤⣶⣶⣶⣶⣿⣿⣿⣿⣿⣿⣷⣾⣿⣿⣿⣿⣿⣿⣿⣏⣀⣀⣀⡀" << endl << "⣿⣿⣿⣿⣿⣿⣿⡿⠿⠛⠛⠻⠿⠟⠉⠉⠉⢻⣿⣿⣿⡿⠟⠋⣡⣼⣿⣿⣿⡄" << endl
<< "⣿⣿⣿⣟⣭⣤⣶⣶⣿⣿⠃⠀⠀⢀⣀⣤⣶⣿⣿⣿⣿⡅⡀⢀⣩⣤⣤⠀" << endl << "⣿⣿⣿⣿⣿⣿⣛⡛⠛⠛⠛⢋⣩⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣛⠛⠛⠓⠠" << endl << "⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⣤⣤⣤⣦" << endl
<< "⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇" << endl << "⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⠿⠿⢿⡿⢿⣿⣿⣿⠃" << endl << "⠿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣥⣄⣀⣀⠀⠀⠀⠀⠀⢰⣾⣿⣿⠏" << endl
<< "⠀⠀⠀⠀⠀⠀⠉⣩⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣜⡻⠋" << endl << "⣰⣾⣷⣶⣿⣾⣖⣻⣿⣿⡿⣿⣿⣿⣿⠿⠿⠟⠛⠛⠛⠋⠉⠉⢉⡽⠃" << endl << "⣿⣿⣿⣿⣿⣿⡉⠉⠉⠛⠛⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⡤⠚⠉" << endl
<< "⠛⠛⣿⣿⣿⣿⣿⣿⣿⠉⠛⢶⣶⣄⠀⠀⠀⠀⠀⠀⠀⠀⡇" << endl << "⠠⣾⣿⣿⣿⣿⣿⠿⠟⠃⠀⠀⠀⠈⠲⣴⣦⣤⣤⣤⣶⡾⠁" << endl << "⠄⠈⠉⠻⢿⣿⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠛⠛⠉⠀" << endl;
cout << endl << mobs[0].name << " has survived!" << endl;
return 0;
}
Mob.h
#ifndef TEXTRPG_MOB_H
#define TEXTRPG_MOB_H
#include <string>
#include <iostream>
using namespace std;
class mob {
int health;
int damage;
int armor;
int attack = 0;
int agility;
void Damage(int attack);
//Types of Attack
void StrongAttack(int& CurrentAttack);
void SmallAttack(int& CurrentAttack);
void Crit(int& CurrentAttack);
public:
string name;
void Return();
void GiveAttack(int& CurrentAttack);
void Attack(int& CurrentAttack);
void TakeHit(int attack);
bool Health();
mob(int health, int damage, int armor, string name, int agility);
};
#endif
Mob.cpp
#include "mob.h"
using namespace std;
//Attack function
void mob::Attack(int& CurrentAttack) {
int n;
cout << "Choose what attack to use:\n1 - Strong Attack;\n2 - Simple Attack;\n3 - Critical Strike;\n";
cin >> n;
switch (n) {
case 1:
StrongAttack(CurrentAttack);
break;
case 2:
SmallAttack(CurrentAttack);
break;
case 3:
Crit(CurrentAttack);
break;
default:
SmallAttack(CurrentAttack);
break;
}
}
//Types of Attack
void mob::StrongAttack(int& CurrentAttack)
{
this -> attack = damage*2;
mob::GiveAttack(CurrentAttack);
}
void mob::SmallAttack(int& CurrentAttack)
{
this -> attack = damage;
mob::GiveAttack(CurrentAttack);
}
void mob::Crit(int& CurrentAttack)
{
if (rand() % 2)
{
this -> attack = damage*3;
mob::GiveAttack(CurrentAttack);
};
}
//Share Attack to main.cpp
void mob::GiveAttack(int& CurrentAttack)
{
CurrentAttack = attack;
}
//TAKE HIT
//Take damage from other mob
void mob::TakeHit(int attack)
{
if (rand()%101 > agility)
{
Damage(attack);
}
else
{
this -> attack = 0;
cout << "You missed" << endl;
}
}
void mob::Damage(int attack) //Health calculation
{
//Damage Calculation
if (attack - armor <= 0)
this -> attack = 0;
else
this -> attack -= armor;
//Health calculation
if (health - attack <= 0)
{
cout << name << " is dead" << endl;
this -> health = 0;//Health < 0 -> Death
}
else
this -> health -= attack; //Health Calculation
}
//Public
void mob::Return()
{
cout << name << " took " << attack << " damage" << endl;
cout << name << " has " << health << " HP left" << endl;
}
bool mob::Health()
{
if (health == 0)
return 0;
else
return 1;
}
//Constructor
mob::mob(int health, int damage, int armor, string name, int agility)
{
this -> health = health;
this -> damage = damage;
this -> armor = armor;
this -> name = name;
this -> agility = agility;
}
I have a class of light bulbs. There are methods and constructors in this class. There is even a destructor) The problem is that I have to determine and display information about class members with type "n" in the TEST() method (LED lamps).
To implement this task, he developed the gettype() method, which returns the type of an object, and, in fact, the TEST() method, which displays information about light bulbs.
The problem is that nothing works for me. I tried a lot of things, but it doesn’t work out for me to implement this task. I'm new to programming (
Code:
#include <iostream>
using namespace std;
class lamp
{
public:
// methods
void TEST(void);
char* gettype (void);
void INIT(void);
void SHOW(void);
// construcrors
lamp();
lamp(const char *t, int powe, const char *c, double cos);
lamp(const lamp & obj);
// destructor
~lamp();
private:
// data
char type[100]; // LED, energy-saving or incandescent lamp
int power; // LED lamp - "n"
char color[100];
double cost;
};
lamp::lamp() {
cout << "This object was created in the default constructor.\n";
strcpy(type, "");
power = 0;
strcpy(color, "");
cost = 0;
}
lamp::lamp(const char *t, int powe, const char *c, double cos) {
cout << "This object was created in the constructor with parameters.\n";
strcpy(type, t); //*t
power = powe;
strcpy(color, c); //*c
cost = cos;
}
lamp::lamp(const lamp & obj) {
cout << "This object was created in the copy constructor.\n";
strcpy(type, obj.type);
power = obj.power;
strcpy(color, obj.color);
cost = obj.cost;
}
lamp::~lamp() {
cout << "Deletion of object by destructor.\n";
}
void lamp::SHOW(void) {
cout << "Lamp Information:\n";
cout << "\nType > " << type;
cout << "\nPower > " << power;
cout << "\nColor > " << color;
cout << "\nCost > " << cost << endl;
}
void lamp::INIT(void) {
cout << "Enter lamp information:\n";
cout << "\nType (if LED, then n) > "; cin >> type;
cout << "\nPower > "; cin >> power;
cout << "\nColor > "; cin >> color;
cout << "\nCost > "; cin >> cost;
}
char* lamp::gettype (void) {
return type;
}
void lamp::TEST(void) {
cout << "\nType > " << type;
cout << "\nPower > " << power;
cout << "\nColor > " << color;
cout << "\nCost > " << cost << endl;
}
void main() {
setlocale(0, "");
// default constructor for 1 class instance
lamp l1;
cout << "Entering data for the first product." << endl;
l1.INIT();
// constructor with parameters for 2 class instances
cout << endl << "Information about the second object: \n";
lamp l2("n", 950, "yellow", 1580);
// copy constructor for the third object
cout << endl << "Information about the third object: \n";
lamp l3(l2);
// Derived information about all the lamps using the method SHOW
l1.SHOW();
l2.SHOW();
l3.SHOW();
// I create an array of two objects using the default constructor
lamp la[2];
I enter data into an array of objects using the method INIT
cout << "Fill an array of objects with 2 elements." << endl;
for(int i = 0; i < 2; i++) {
la[i].INIT();
}
// I output data from an array of objects using the method SHOW
cout << "Showing items." << endl;
for (int i = 0; i < 2; i++) {
la[i].SHOW();
}
// looking for and displaying information about LED lamps
cout << "Search and display information about LED lamps." << endl;
for (int i = 0; i < 3; i++) {
if (la[i].gettype() == "n") {
cout << endl << " lamp number : " << (i + 1) << endl;
la[i].TEST();
cout << endl;
}
}
system("pause");
}
There are several errors in your code:
strcpy is included in <cstring> which is missed. You need to add it in the beginning:
#include <cstring>
main() function should be declared as int main() and you need to add a return statement
int main() {
//YOUR CODE HERE
return 0;
}
You missed a comment sign at line 104
lamp la[2];
//I enter data into an array of objects using the method INIT
cout << "Fill an array of objects with 2 elements." << endl;
After fixed, your code should be able to run.
Hi this is the header file for my base class Ranger, and in it I have protected variables fov_, usb_ ... that I wish to access with my getter functions, I have three child classes on this one.
Ranger.h
#ifndef RANGER_H
#define RANGER_H
using namespace std;
class Ranger
{
//private contructor prevents contruction of base class
Ranger();
public:
void setBaud(int baud);
virtual void setFOV(int fov) = 0;
void setSamp(int sam);
int getFOV();
int getBaud();
int getMaxRange();
int getUSB();
protected:
//protected variables that are each indivdualy owned by each sensor
int fov_;
int maxRange_;
int usb_;
int baud_;
int samp_;
double data[];
//protected contructors for the child classes to use to set fixed parameters
Ranger(int fov, int maxRange, int port);
Ranger(int maxRange, int port);
};
#endif // RANGER_H
This is my cpp file for the base class that includes the getter files, it just has a return of the portected variables.
Ranger::Ranger()
{
}
Ranger::Ranger(int fov, int maxRange, int port)
{
fov_ = fov;
maxRange_ = maxRange;
usb_ = port;
}
Ranger::Ranger(int maxRange, int port)
{
maxRange_ = maxRange;
usb_ = port;
}
void Ranger::setBaud(int baud)
{
switch(baud)
{
case 0: baud_ = 38400; break;
case 1: baud_ = 115200; break;
default: baud_ = 38400; break;
}
}
void Ranger::setSamp(int sam)
{
samp_ = sam;
}
int Ranger::getFOV()
{
return fov_;
}
int Ranger::getBaud()
{
return baud_;
}
int Ranger::getMaxRange()
{
return maxRange_;
}
int Ranger::getUSB()
{
return usb_;
}
And in my main I want to access the protected variables from the base class to prevent re writting code, so each childs variables are protected in the base class. I try to access these by las.getFOV() but I get a segmentation fault error meaning I don't have access to them, and I don't quite understand why.
main.cpp
int main( int argc, char ** argv)
{
Laser las;
int baud;
cout << "Baud:" << endl;
cout << "0 - 38400" << endl;
cout << "1 - 115200" << endl;
cin >> baud;
las.setBaud(baud);
cout << "Baud for Lazer sensor is "+las.getBaud() << endl;
cout << "Lazer sensor created..." << endl;
cout << "Lazer's FOV: " + las.getFOV() << endl;
cout << "Lazer's Max Range: " + las.getMaxRange() << endl;
cout << "Lazer's Port: " + las.getUSB() << endl;
Radar rad;
int baud2;
cout << "Baud:" << endl;
cout << "0 - 38400" << endl;
cout << "1 - 115200" << endl;
cin >> baud2;
rad.setBaud(baud2);
cout << "Baud for Radar sensor is "+rad.getFOV() << endl;
int fov;
cout << "Feild of View Of Radar:" << endl;
cout << "0 - 20 degrees" << endl;
cout << "1 - 40 degrees" << endl;
cin >> fov;
rad.setFOV(fov);
cout << "FOV is set to " + rad.getFOV() << endl;
cout << "Radar sensor created..." << endl;
cout << "Radar's FOV: ' " + rad.getFOV() << endl;
cout << "Radar's Max Range: " + rad.getMaxRange() << endl;
cout << "Radar's Port: " + rad.getUSB() << endl;
Sonar son;
//rad.setFOV(user);
}
and here is one of the child class's cpp file for reference (Lazer)
laser.cpp
#include "laser.h"
Laser::Laser() : Ranger(180,8,0)
{
};
void Laser::setFOV(int fov)
{
fov_ = fov;
}
laser.h
#ifndef LASER_H
#define LASER_H
#include "ranger.h"
#include "rng.h"
class Laser : public Ranger
{
public:
Laser();
void setFOV(int fov);
};
#endif // LASER_H
Thanks everyone who commented, I understand I put way too much code to help you guys out, sorry about that I'll know for next time, and thankyou to letting me know the difference between the errors, I've done more research and found that the issue was when I was printing it out you can't use operators like:
cout<<""+function()<<endl;
Instead you need to separate the functions from the array like so:
cout<<""<<function()<<endl;
Thanks guys.
Compiles and everything except adding in a 'ship'
Constructor for ship
Ship::Ship(std::string name, int length, std::string show) {
std::string _name = name;
int _length = length;
std::string _show = show;
}
void Ships::buildShip() {
std::string name, show;
int length = 0;
std::cout << "What is the name of the ship? ";
std::cin >> name;
std::cout << "How long is the ship in feet? ";
std::cin >> length;
std::cout << "What show/movie is the ship from? ";
std::cin >> show;
std::cout << std::endl;
Ship ship(name, length, show);
addShip(ship);
}
void Ships::addShip(Ship &ship) {
ships.push_back(ship);
}
I'm sure it's something very obvious, I've searched the web and found nothing helpful. I only took snippets from my code if anything else is needed let me know. Thanks in advance!
/Ship.h
#pragma once
#include <string>
class Ship {
std::string _name;
int _length;
std::string _show;
public:
Ship(){
std::string name = _name;
int length = _length;
std::string show = _show;
};
Ship(std::string _name, int _length, std::string _show);
std::string getName();
int getLength();
std::string getShow();
};
/Ship.cpp
#include <string>
#include "Ship.h"
Ship::Ship(std::string name, int length, std::string show) {
std::string _name = name;
int _length = length;
std::string _show = show;
}
std::string Ship::getName() {
return _name;
}
int Ship::getLength() {
return _length;
}
std::string Ship::getShow() {
return _show;
}
/Ships.h
#pragma once
#include <vector>
#include "Ship.h"
class Ships {
std::vector<Ship> ships;
public:
void addShip(Ship &ship);
int getCount();
Ship getLongestShip();
void buildShip();
int getNumberOfShipsLongerThan(int input);
void displayShips();
};
/Ships.cpp
#include "Ships.h"
#include <iostream>
void Ships::addShip(Ship &ship) {
ships.push_back(ship);
}
int Ships::getCount() {
return ships.size();
}
Ship Ships::getLongestShip() {
Ship longestShip = ships[0];
for (Ship aShip : ships) {
if (longestShip.getLength() < aShip.getLength())
longestShip = aShip;
}
std::cout << "The longest ship is the " << longestShip.getName() << std::endl;
std::cout << "From end to end the length is " << longestShip.getLength() << std::endl;
std::cout << "The show/movie it is from is " << longestShip.getShow() << std::endl;
return longestShip;
}
int Ships::getNumberOfShipsLongerThan(int input) {
int longerThan = 0;
int size = ships.size();
for (int i = 0; i < size; i++) {
if (input < ships[i].getLength())
longerThan++;
}
return longerThan;
}
void Ships::displayShips() {
std::cout << " Complete Bay Manifest " << std::endl;
std::cout << "***********************" << std::endl;
for (int i = 0; i < ships.size(); i++) {
int a = i + 1;
std::cout << "Ship (" << a << ")" << std::endl;
std::cout << "Name: " << ships[i].getName() << std::endl;
std::cout << "Length: " << ships[i].getLength() << std::endl;
std::cout << "Show: " << ships[i].getShow() << std::endl<<std::endl;
}
}
void Ships::buildShip() {
std::string name, show;
int length = 0;
std::cout << "What is the name of the ship? ";
std::cin >> name;
std::cout << "How long is the ship in feet? ";
std::cin >> length;
std::cout << "What show/movie is the ship from? ";
std::cin >> show;
std::cout << std::endl;
Ship ship(name, length, show);
addShip(ship);
}
/driver.cpp
#include <iostream>
#include "Ship.h"
#include "Ships.h"
void menu();
Ship buildShip();
void shipsInBay(Ships &ships);
void processDirective(int choice, Ships &ships);
void longerThan(Ships &ships);
int main() {
std::cout << "Welcome to Daniel Mikos' Ship Bay!" << std::endl << std::endl;
menu();
system("PAUSE");
return 0;
}
void menu() {
Ships ships;
int choice = 0;
std::cout << "Please make a selection" << std::endl;
std::cout << " (1) Add a ship to the bay" << std::endl;
std::cout << " (2) How many ships are already in the bay?" << std::endl;
std::cout << " (3) Which ship is the longest? " << std::endl;
std::cout << " (4) Ships longer than ___? " << std::endl;
std::cout << " (5) Manifest of all ships currently logged" << std::endl;
std::cout << " (6) Exit" << std::endl;
std::cout << " Choice: ";
std::cin >> choice;
processDirective(choice, ships);
}
Ship buildShip() {
std::string name, show;
int length = 0;
std::cout << "What is the name of the ship? ";
std::cin >> name;
std::cout << "How long is the ship in feet? ";
std::cin >> length;
std::cout << "What show/movie is the ship from? ";
std::cin >> show;
std::cout << std::endl;
Ship ship(name, length, show);
return ship;
}
void shipsInBay(Ships &ships) {
int count = ships.getCount();
std::cout << std::endl;
std::cout << "There is currently " << count;
std::cout << " ship(s) in bay" << std::endl << std::endl;
}
void longerThan(Ships &ships) {
int input = 0;
std::cout << "Find ships longer than? ";
std::cin >> input;
std::cout << "There are " << ships.getNumberOfShipsLongerThan(input) << "longer than " << input << "feet";
}
void processDirective(int choice, Ships &ships) {
if (choice == 1)
buildShip();
if (choice == 2)
shipsInBay(ships);
if (choice == 3)
ships.getLongestShip();
if (choice == 4)
longerThan(ships);
if (choice == 5)
ships.displayShips();
menu();
}
There is all of my code
To add an object to a vector of objects use emplace_back() and pass the constructor arguments as arguments to emplace back. It will then build the object in place so call:
ships.emplace_back(name, length, show);
to construct your ship object in place. Your constructor also is incorrect as pointed out by #Kevin. You need to change it to:
this->_name = name;
this->_length = length;
this->_show = show;
assuming I've guessed your class design correctly.
EDIT
Tried to build a minimum example from this and this works fine for me:
Header.h
class Ship {
std::string _name;
int _length;
std::string _show;
public:
Ship();
Ship(std::string _name, int _length, std::string _show);
std::string getName();
int getLength();
std::string getShow();
};
class Ships {
public:
void addShip(Ship &ship);
void buildShip();
std::vector<Ship> ships;
};
and Source.cpp
#include "Header.h"
Ship::Ship(std::string name, int length, std::string show) {
this->_name = name;
this->_length = length;
this->_show = show;
}
void Ships::buildShip() {
std::string name = "Name";
std::string show = "Show";
int length = 0;
ships.emplace_back(name, length, show);
}
int main(int argc, char argv[])
{
Ships ships;
ships.buildShip();
std::cout << "Number of ships = " << ships.ships.size() << std::endl;
return 0;
}
Prints Number of ships = 1. Can you slim it down to something like this?