Calling argument in parametrized constructor in method - C++ - c++

I'm new at programming. I wondered if you were to call a specific argument in the parameter for your constructor, which you had to use in your method, then how would you do it with pointers? I solved it by the use of 'this' because the local variable name is the same as the member variable's name, but I just wanted to see how it is possible by the use of normal pointers and not the this pointer.
Here is the code I worked on.
BMR.h
#include <string>
using namespace std;
class BMR
{
public:
BMR();
BMR(char, int, int, int);
int calculateBMR();
private:
int weight;
int height;
int age;
char gender;
};
BMR.cpp
#include "BMR.h"
#include <iostream>
using namespace std;
BMR::BMR()
{
}
BMR::BMR(char k, int h, int w, int a)
{
gender = k;
height = h;
weight = w;
age = a;
}
int BMR::calculateBMR()
{
int BMR;
if(this->gender == 'M')
{
BMR = 10 * weight + (6.25 * height - (5*age)) + 5;
cout << "Man: " << BMR << endl;
}
if(this->gender == 'W')
{
BMR = 10 * weight + (6.25 * height - (5*age)) - 161;
cout << "Woman: " << BMR << endl;
}
}

Related

C++ Setter doesn't change the object's variable value

I'm trying to run a code that its's meant to change the value of object variables after it creates the object, and it isn't changing, then the variable is returning values like -815470397 and not changing. And when I use breakpoints it's like it jumps the inside part of the setter.
Pessoa.h
#pragma once
using namespace std;
class Pessoa
{
protected:
int dia;
int mes;
int ano;
int idade;
public:
Pessoa();
Pessoa(int, int, int, int);
int GetDia();
void SetDia(int);
int GetMes();
void SetMes(int);
int GetAno();
void SetAno(int);
int GetIdade();
void SetIdade(int);
};
Pessoa.cpp
#include "Pessoa.h"
Pessoa::Pessoa() {
}
Pessoa::Pessoa(int dia, int mes, int ano, int idade) {
this->dia = dia;
this->mes = mes;
this->ano = ano;
this->idade = idade;
}
int Pessoa::GetDia() {
return this->dia;
}
int Pessoa::GetMes() {
return this->mes;
}
int Pessoa::GetAno() {
return this->ano;
}
int Pessoa::GetIdade() {
return this->idade;
}
void Pessoa::SetDia(int dia) {
this->dia == dia;
}
void Pessoa::SetMes(int mes) {
this->mes == mes;
}
void Pessoa::SetAno(int ano) {
this->ano == ano;
}
void Pessoa::SetIdade(int idade) {
this->idade == idade;
}
Exame_especial.cpp
#include <iostream>
#include <string>
#include "Pessoa.h"
using namespace std;
string ImprimeIdade(Pessoa*);
int Calc_Idade(Pessoa*, int, int, int);
int main()
{
Pessoa* Einstein = new Pessoa();
Pessoa* Newton = new Pessoa();
Einstein->SetDia(14);
Einstein->SetMes(3);
Einstein->SetAno(1879);
Newton->SetDia(4);
Newton->SetMes(1);
Newton->SetAno(1643);
cout << ImprimeIdade(Newton) << endl;
cout << ImprimeIdade(Einstein) << endl;
}
string ImprimeIdade(Pessoa* nome) {
nome->SetIdade(Calc_Idade(nome, 29, 6, 2021));
return "A idade de Einstein seria " + to_string(nome->GetIdade()) + "\n";
}
int Calc_Idade(Pessoa* nome, int dia, int mes, int ano) {
int idade = ano - nome->GetAno();
if (nome->GetMes() > mes) {
idade = idade - 1;
}
else {
if (nome->GetMes() == mes) {
if (nome->GetDia() > dia) {
idade = idade - 1;
}
}
}
return idade;
}
You get these strange values due to the fact that your data members are of built-in type and they remain uninitialized when you use them. They remain uninitialized because your setters aren't setting anything. What they actually do is a comparison (the ==).
Pay attention to the difference in these two:
void Pessoa::SetDia(int dia) {
this->dia == dia; // Equal? Returns bool value which is lost
}
Vs
void Pessoa::SetDia(int new_dia) {
this->dia = new_dia; // Assigns a new value
}
This goes for all setters in your code.
Also, note that inside the body of a member function, you can refer to the data members directly, without the need to dereference them via this:
void Pessoa::SetDia(int new_dia) {
// Assigns new value to the dia data member of this
dia = new_dia;
}

Why does this happen c++ [duplicate]

This question already has answers here:
string and int concatenation in C++ [duplicate]
(3 answers)
Closed 2 years ago.
Hello I am trying to make a game somewhat like Pokemon but I'm stuck on printing stats.
I am trying to output a level with it showing what level the animal reached.
Any help on the fact I'm not getting expected results?
My code:
visualanimal.h (not used yet):
#include <string>
#ifndef VISUALANIMAL_H
#define VISUALANIMAL_H
using namespace std;
using namespace Animals;
/*** Visual based on original class
#author Adam Petla
***/
class VisualAnimal : Animal {
public:
string imageFileURL;
int size;
VisualAnimal() {
this->imageFileURL = "";
this->size = 0;
}
};
#endif
animal.h :
#include <string>
#include <stdio.h>
#include <iostream>
#ifndef ANIMAL_H
#define ANIMAL_H
using namespace std;
namespace Animals {
class Animal {
public:
string name;
int minlevel;
int level;
int maxlevel;
int baseattack;
int baseattackraise;
int attack;
int basedefense;
int basedefenseraise;
int defense;
int basespeed;
int basesppedraise;
int speed;
int basespecial;
int basespecialraise;
int special;
char type;
Animal() {
name = "DOG";
minlevel = 0;
level = 1;
maxlevel = 100;
baseattack = 1;
baseattackraise = 1;
basedefense = 1;
basedefenseraise = 1;
basespecial = 1;
basespecialraise = 1;
basespeed = 1;
basesppedraise = 1;
};
private:
void printstats() {
//cout << "Attack : " << this->
};
void raiseattack() {
this->attack += this->baseattackraise;
}
void raisedefense() {
this->defense += this->basedefenseraise ;
}
void raisespeed() {
this->speed += this->basesppedraise;
}
void raisespecial() {
this->special += this->basespecialraise;
}
void raisestats() {
raiseattack();
raisedefense();
raisespeed();
raisespecial();
}
void updatestats(char type) {
switch (type) {
case 'l':
raisestats();
}
}
public :
void raiselevel() {
this->level++ ;
this->type = 'l';
updatestats(this->type);
string output = "Level Up!Your " + string(this->name) + string("has reached level");
cout << output;
cout << this->level + ".Its stats are now";
printstats();
};
};
}
#endif
animal.cpp :
// Animals.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "animal.h"
#include "visualanimal.h"
using namespace std;
int main()
{
using namespace`` Animals;
Animal test;
test.raiselevel();
cout << "Hello World!\n";
return -1;
}
My expected results: DOG reached level 2.
My actual results DOG reached level
Anybody know an answer
It doesn't show any level in output anybody know why?
Change the following:
cout << this->level + ".Its stats are now";
To:
cout << this->level << ".Its stats are now";
You were getting incorrect output because you are trying to concatenate a string and an int.
The correct way to concatenate a string to an int is using std::to_string():
int val = 2;
std::string x = "hello";
std::string output = std::to_string(val) + x;
+ has a higher precedence than <<, so the line cout << this->level + ".Its stats are now"; is evaluated as cout << (this->level + ".Its stats are now"); - the value of level is used as an offset into a string literal ".Its stats are now", which is not what you want.
Change it to
cout << this->level << ".Its stats are now";
Or see here how to concatenate an int with a string.

Fuction-definition not allowed RetailItem

I got some problem when run my coding. I got 2 separate file to create RetailItem class and create main. I create both in project.
Below are main.cpp
//main
#include "retailitem.h"
#include <iostream>
#include <iomanip>
using namespace std;
using std::cout;
void displayItem(RetailItem *, const int);
int main()
{
const int Item = 3;
RetailItem ritem[Item] ={ { "Jacket", 12, 59.95 },
{ "Designer Jeans", 40, 34.95 },
{ "Shirt", 20, 24.95 } };
//cout << fixed << setprecision(2);
void displayItem(RetailItem *ritem, const int Item){
cout <<" DESCRIPTION UNITS ON HAND PRICE";
cout<<"=================================================================\n";
for (int i = 0; i < Item; i++)
{
cout << setw(12) << ritem[i].getDesc();
cout << setw(12) << ritem[i].getUnits();
cout << setw(8) << ritem[i].getPrice();
}
cout << "===================================================================";
}
return 0;
}
and there one more file retailitem.h
//RetailItem class
#include <string>
using namespace std;
class RetailItem
{
private:
string description;
int unitsOnHand;
double price;
public:
RetailItem(string,int,double);
void setDesc(string d);
void setUnits(int u);
void setPrice(double p);
string getDesc();
int getUnits();
double getPrice();
};
RetailItem::RetailItem(string desc, int units, double cost)
{
description = desc;
unitsOnHand = units;
price = cost;
}
void RetailItem::setDesc(string d)
{
description = d;
}
void RetailItem::setUnits(int u)
{
unitsOnHand = u;
}
void RetailItem::setPrice(double p)
{
price = p;
}
string RetailItem::getDesc()
{
return description;
}
int RetailItem::getUnits()
{
return unitsOnHand;
}
double RetailItem::getPrice()
{
return price;
}
when compile and run main,
[Error] a function-definition is not allowed here before '{' token
[Error] expected '}' at end of input
I don't know what to fix, how can I solve it?
The error message undoubtedly contained a line number that told you where the problem was. That's an important part of describing the problem. But here it happens to be obvious: void displayItem(RetailItem *ritem, const int Item){ is the start of a function definition. You can't define a function inside another function. Move this outside of main.

Class name does not name a type - Pulling my hair out

I've been working on this for several hours and I can't figure out which class is giving me problems. I get a bunch of 'VendSlot' does not name a type" errors. I appreciate any help you can provide. I am new to C++ and extremely frustrated.
//class Snack
#ifndef SNACK_HPP
#define SNACK_HPP
#include <iostream>
#include <string>
using namespace std;
class Snack
{
private:
string name;
double price;
int calories;
public:
Snack();
Snack(string name, double price, int calories);
string getName();
double getPrice();
int getNumCalories();
};
#endif
Snack.cpp
#include "Snack.hpp"
#include <iostream>
#include <string>
using namespace std;
Snack::Snack()
{
name = "bottled water";
price = 1.75;
calories = 0;
}
Snack::Snack(string n, double p, int c)
{
name = n;
price = p;
calories = c;
}
string Snack::getName()
{
return name;
}
double Snack::getPrice()
{
return price;
}
int Snack::getNumCalories()
{
return calories;
}
VendSlot.hpp
#ifndef VENDSLOT_HPP
#define VENDSLOT_HPP
#include "Snack.hpp"
class VendSlot
{
private:
Snack s;
int amount;
public:
VendSlot();
VendSlot(Snack s, int a);
Snack getSnack();
int getAmount();
int decrementAmount();
};
#endif
VendSlot.cpp
#include "VendSlot.hpp"
#include <iostream>
#include <string>
using namespace std;
VendSlot();
VendSlot::VendSlot()
{
Snack s1;
s = s1;
amount = 5;
}
VendSlot::VendSlot(Snack s1, int a)
{
s = s1;
amount = 5;
}
Snack VendSlot::getSnack()
{
Snack s1;
s = s1;
return s;
}
int VendSlot::getAmount()
{
return amount;
}
int VendSlot::decrementAmount()
{
amount--;
return amount;
}
MiniVend.hpp
#ifndef MINIVEND_HPP
#define MINIVEND_HPP
#include "VendSlot.hpp"
class MiniVend
{
private:
VendSlot vs1;
VendSlot vs2;
VendSlot vs3;
VendSlot vs4;
double money;
public:
MiniVend();
MiniVend(VendSlot v1, VendSlot v2, VendSlot v3, VendSlot v4, double money);
int numEmptySlots();
double getMoney();
double valueOfSnacks();
void buySnack();
};
#endif
MiniVend.cpp
#include "VendSlot.hpp"
using namespace std;
MiniVend::MiniVend(VendSlot v1, VendSlot v2, VendSlot v3, VendSlot v4, double m)
{
vs1 = v1;
vs2 = v2;
vs3 = v3;
vs4 = v4;
money = m;
}
double MiniVend::getMoney()
{
return money;
}
int MiniVend::numEmptySlots()
{
int numSlots = 0;
if (vs0.getAmount() == 0)
slots++;
if (vs1.getAmount() == 0)
slots++;
if (vs2.getAmount() == 0)
slots++;
if (vs3.getAmount() == 0)
numSlots++;
return numSlots;
}
double MiniVend::valueOfSnacks()
{
double value = 0;
value = (vs0.getSnack().getPrice() * vs0.getAmount() +
(vs1.getSnack().getPrice() * vs1.getAmount()) +
(vs2.getSnack().getPrice() * vs2.getAmount()) +
(vs3.getSnack().getPrice() * vs3.getAmount()))
return value;
}
void MiniVend::buySnack(int slot);
{
if (slot == 0 && vs0.getAmount >= 1)
{
money = money + vs0.getSnack.getPrice();
vs0.decrementAmount();
}
else if (slot == 1 && vs1.getAmount >= 1)
{
money = money + vs1.getSnack.getPrice();
vs1.decrementAmount();
}
else if (slot == 2 && vs2.getAmount >= 1)
{
money = money + vs2.getSnack.getPrice();
vs2.decrementAmount();
}
else if (slot == 3 && vs3.getAmount >= 1)
{
money = money + vs3.getSnack.getPrice();
vs3.decrementAmount();#include "Snack.hpp"
}
else
cout << "Sold out. Please select another Snack." << endl;
}
Main
#include "MiniVend.hpp"
#include "Snack.hpp"
#include "VendSlot.hpp"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Snack s2("candy bar", 1.25, 300);
Snack s3("root beer", 2.00, 450);
VendSlot groucho(s1, 2);
VendSlot harpo(s2, 1);
VendSlot chico(s3, 0);
VendSlot zeppo; // five bottles of water
MiniVend machine(groucho, harpo, chico, zeppo, 0);
cout << machine.numEmptySlots() << endl;
cout << machine.valueOfSnacks() << endl;
cout << machine.getMoney() << endl;
machine.buySnack(1);
cout << machine.numEmptySlots() << endl;
cout << machine.valueOfSnacks() << endl;
cout << machine.getMoney() << endl;
return 0;
}
At MiniVend.hpp your buySnack does not take any parameters void buySnack();, but at Minivend.cpp you are defining an argument at your function header
void MiniVend::buySnack(int slot);, and you shouldn't be using an semicolon too.
Your MiniVend.cpp file should also include the "MiniVend.hpp" header as well.
At MiniVend.cpp in the declaration of function int MiniVend::numEmptySlots() vs0 is not defined anywhere in the code as well as slots
At you main function you are trying to declare this VendSlot groucho(s1, 2);, but you have not defined s1 anywhere in your main function
That's what I have found so far. Hope this helps and please use comments when posting a question so that everyone can understand the purpose of the code.

Is it possible for objects to be parameters in functions?

I have written a snippet that tries to use an object from a class as a function parameter, and I keep getting the error
In function 'int main()':
75:23: error: expected primary-expression before 'test'
75:35: error: expected primary-expression before 'Knight'
I am not sure how to fix this, as I am quite new to C++.
Some example code is down below:
// Example program
#include <iostream>
#include <string>
using namespace std;
//player class
class Player {
public:
//variable declaration
string name;
string classType;
int strength, perception, endurance, charisma, intelligence, agility, luck;
int id, cubes; // currency etc.
bool authority;
int inventory[20] = {};
int health = 100 + ((strength * endurance) * 2);
//sub stat functions
double getPick() {
return ((intelligence + luck) * (agility / 4)) * .01;
}
double getSneak() {
return (25 + (agility * 5)) * 0.01;
}
double getIntimidation() {
return (charisma * 10) * 0.01;
}
double getBarter() {
return getIntimidation();
}
double getScience() {
return ((intelligence * 5) / 3);
}
};
//enemys
class enemy {
public:
//var declaration
string name;
int HP;
double AC; //armor class ablity to resist hits
int DT; //dice used to attack
int eid; //id for enemys (enemy id)
int gear[2] = {}; //gear
//is the enemy alive?
int alive() {
if (HP <= 0) cout << "\nThe " << name << " is dead! ";
return false;
}
};
//fight an enemy (option 1)
int fightEnemy(Player player1, enemy enemy1) {
cout << "\n" << player1.name << " and a " << enemy1.name << "\n";
return 0;
}
int main() {
//test
Player test;
test.name = "test";
test.classType = "test";
test.strength = 3;
test.perception = 3;
test.endurance = 6;
test.charisma = 2;
test.intelligence = 6;
test.agility = 3;
test.luck = 5;
test.id = 1;
test.authority = true;
test.cubes = 500;
enemy Knight;
Knight.name = "Knight";
Knight.HP = 20;
Knight.AC = 0.2;
Knight.DT = 12;
Knight.eid = 3;
fightEnemy(Player test, enemy Knight);
return 0;
}
fightEnemy(Player test, enemy Knight);
Syntax is wrong here. You just pass the variables to the function, you are essentially declaring them again.
It should be
fightEnemy(test, Knight);
fightEnemy(Player test, enemy Knight);
to
fightEnemy(test, Knight);
The variables are already initialized.