object is undefined in function - c++

Im new to C++ and started working with classes recently for a school excercice.
I really cant see whats wrong and after creating an object "player" to the Hero class i can't use that object later in the "main Menu" function to call a method because i get the "identifier is undefined" error!
Any suggestions?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Hero
{
private:
//member variables
string playername;
public:
//constructor
Hero(string name)
{
playername = name;
}
string getName()
{
return playername;
}
};
//start 1
void mainMenu()
{
cout << " - - - |" << player.getName() << "- - - \n";
}
void setPlayer()
{
string name;
cout << "Hello, what is your name? " << endl;
getline(cin, name);
Hero player(name);
mainMenu();
}
int main()
{
int selection;
cout << "Shadow of darkness\n ";
cout << "1.) Start ";
cout << "2.) Exit ";
cin >> selection;
if (selection == 1)
setPlayer();
else if (selection == 2)
exit (0);
else
main();
return 0;
}

OK, calling main() from main() is a forbidden (as explained here), so do not do it.
Here is a typical example with your class (the class is cool as you have it, I just added an initializer list for fun):
#include <iostream>
#include <string>
using namespace std;
class Hero
{
private:
//member variables
string playername;
public:
//constructor
Hero(string name) : playername(name)
{
}
string getName()
{
return playername;
}
};
int main()
{
Hero player("Daniel");
cout << "Player's name: " << player.getName() << std::endl;
return 0;
}
Output:
Player's name: Daniel
Based on this, try to work your logic and do all sort of stuff that you long for (after reading some books/tutorials)!

Related

Why the function doesn't recognize an object created in main()?

I have to make a Shopping Cart program for school, and there are more moving parts in this program than I've ever had to deal with. I'm trying to figure out why the function in my main.cpp can't recognize the object that I created in main(). It keeps saying that
the cart is not declared in the scope.
I still have to finish building out the menu, but I can't even get it to recognize the object that gets created in main.
I can see that the object is being properly created, because it can be manipulated within the main() no problem. Furthermore, I even have a few placeholder commands in there to get it working. The thing is that the homework assignment requires the menu to be in a function.
#include <iostream>
#include <string>
#include "ItemToPurchase.h"
#include "ShoppingCart.h"
using namespace std;
void PrintMenu()
{
while (true)
{
string choice;
cout << "MENU" << endl;
cout << "a - Add item to cart" << endl;
cout << "d - Remove item from cart" << endl;
cout << "c - Change item quantity" << endl;
cout << "i - Output item's descriptions" << endl;
cout << "o - Output shopping cart" << endl;
cout << "q - Quit" << endl;
cout << endl;
cout << "Choose an option: " << endl;
cin >> choice;
if (choice == "a") {
cart.GetDate();
}
else if (choice == "d") {
}
else if (choice == "c") {
}
else if (choice == "i") {
}
else if (choice == "o") {
}
else if (choice == "q") {
break;
}
else {
cout << "That is not a valid choice" << endl;
}
}
}
int main()
{
string name;
string date;
cout << "Enter customer's name: " << endl;
cin >> name;
cout << "Enter today's date: " << endl;
cin >> date;
cout << endl;
cout << "Customer name: " << name << endl;
cout << "Today's date: " << date << endl;
ShoppingCart cart(name, date);
ItemToPurchase apple("apple", 1, 4, "apple");
cout << cart.GetDate();
cart.AddItem(apple);
cout << cart.GetNumItemsInCart();
PrintMenu();
}
#ifndef SHOPPINGCART_H
#define SHOPPINGCART_H
#include <string>
#include <iostream>
#include <vector>
#include "ItemToPurchase.h"
using namespace std;
class ShoppingCart
{
private:
string customerName = "none";
string currentDate = "January 1, 2016";
vector<ItemToPurchase> cartItems;
public:
ShoppingCart(string name, string date);
string GetCustomerName() const;
string GetDate();
void AddItem(ItemToPurchase);
void RemoveItem(string);
void ModifyItem();
int GetNumItemsInCart();
double GetCostofCart();
void PrintTotal();
string PrintDecriptions();
};
#endif
#include <iostream>
#include <string>
#include <vector>
#include "ShoppingCart.h"
using namespace std;
ShoppingCart::ShoppingCart (string name, string date){
customerName=name;
currentDate= date;
}
string ShoppingCart::GetCustomerName() const
{
return customerName;
}
string ShoppingCart::GetDate()
{
return currentDate;
}
void ShoppingCart::AddItem(ItemToPurchase item)
{
cartItems.push_back(item);
}
void ShoppingCart::RemoveItem(string name)
{
for (int i = 0; i < cartItems.size(); i++)
{
if (cartItems.at(i).GetName() == name)
{
cartItems.erase(cartItems.begin() + i);
}
else
{
cout << "Item not found in cart. Nothing removed." << endl;
}
}
}
int ShoppingCart::GetNumItemsInCart(){
int number;
number = cartItems.size();
return number;
}
double ShoppingCart::GetCostofCart()
{
double sum = 0.0;
for (int i = 0; i < cartItems.size(); i++)
{
sum += cartItems[i].GetQuantity() * cartItems[i].GetPrice();
}
return sum;
}
#include "ItemToPurchase.h"
void ItemToPurchase::SetName(string SetItemName){
itemName = SetItemName;
}
void ItemToPurchase::SetPrice(int SetItemPrice){
itemPrice = SetItemPrice;
}
void ItemToPurchase::SetQuantity(int SetItemQuantity){
itemQuantity = SetItemQuantity;
}
string ItemToPurchase::GetName() const {
return itemName;
}
int ItemToPurchase::GetPrice() const {
return itemPrice;
}
int ItemToPurchase::GetQuantity() const {
return itemQuantity;
}
#include <string>
#include <iostream>
#ifndef ITEMTOPURCHASE_H
#define ITEMTOPURCHASE_H
using namespace std;
class ItemToPurchase
{
public:
ItemToPurchase(string a, int b, int c, string d)
{itemName = a;
itemPrice = b;
itemQuantity = c;
itemDescription =d;
}
void SetName(string SetItemName);
void SetPrice(int SetItemPrice);
void PrintItemDescription();
void SetQuantity(int SetItemQuantity);
string GetName() const;
int GetPrice() const;
int GetQuantity() const;
void SetDescription() const;
string GetDiscription() const;
void PrintItemCost() const;
private:
string itemName;
int itemPrice;
int itemQuantity;
string itemDescription;
};
#endif
[...], but I can't even get it, to recognize the object that gets created in main().
The main() and the PrintMenu() are two different functions with different scope. One can not know the variables from other, unless you pass or make known by any means.
In your case, you can pass the ShoppingCart object (i.e cart) from main() to the PrintMenu function, so that inside it will know which cart you meant for:
void PrintMenu(ShoppingCart& cart)
// ^^^^^^^^^^^^^^^^^^^^
{
// ...
}
and call the function from main() with the ShoppingCart object.
PrintMenu(cart);
That being said;
Please do not practice with using namespace std;. Read more: Why is "using namespace std;" considered bad practice?
If the member function does not modify the member, you should mark the function as const. Applies for all the getters of both ItemToPurchase and ShoppingCart classes.
When you return a non-trivial copyable objects like std::string in a getter, you should be avoiding copying. That means you might want to have changes like as below for all your getters which returns std::string:
const std::string& GetDate() const /* noexcept */
{
return currentDate;
}
This line in PrintMenu is the problem:
cart.GetDate();
The compiler looks for something called cart within the scope of that function, which does not exist. Once way to resolve this, is to pass a reference to the cart created in main to the PrintMenu function:
void PrintMenu(ShoppingCart &cart){
and call the function like this:
PrintMenu(cart);
Note that because, in the future, you'll want to modify cart in the menu, you'll need to pass it as a reference (i.e. with &) and not as a copy or constant reference.

C++ Text-Based RPG Inventory System

I'm currently taking a programming 2 class (c++), we've been tasked to make a text based rpg. I'm using this post as a reference for my inventory system, as I think it's pretty effective. But I keep running into a E0349 "no operator "==" or "<<" matches these opperands" error.
If anyone could help me that would be great. Here is my full set of code:
#include "pch.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <ostream>
#include <Windows.h>
#include <string>
#include <cctype>
using namespace std;
struct Item {
string name; //Item name.
int slot; //Head, Torso, Hands
int attack;
int knowledge;
int defense;
int hp;
int speed;
int charisma;
};
int main()
{
//Variables, Strings, etc.
int itemcounter = 0, counter = 0;
//"Empty" Item
Item Empty{ "<Empty>", 0, 0, 0 };
vector<Item> Equipment = { 6, Empty }; //Current Equipment, 6 empty slots.
vector<Item> Inventory = { }; //Player Inventory.
string InventorySlots[] = { "Head" "Torso", "Hands" }; //Player parts where items can be equiped.
cout << "You sit your bag down and take a look inside." << " You have:" << endl;
for (int i = 0; i < itemcounter; i++)
{
cout << InventorySlots[i];
if (Equipment[i] == "Empty ")
{
cout << " " << Equipment[i] << endl << endl;
}
}
}
Here is where my errors are more specifically
for (int i = 0; i < itemcounter; i++) //Display equipped
{
cout << InventorySlots[i];
if (Equipment[i] == "Empty ") //Error Here
{
cout << " " << Equipment[i] << endl << endl; //Errore Here
}
}
Error Message
Error (active) E0349 no operator "<<" matches these operands C:\Users\USER\source\repos\clunkinv\clunkinv\clunkinv.cpp 47
Equipment[i] is an object of type Item. If you don't provide a method to compare your object with "Empty" the compiler can't know how to compare in line
if (Equipment[i] == "Empty ")
Either you compare the property
if (Equipment[i].name == "Empty ")
or you have to provide a method. Same problem in line
cout << " " << Equipment[i] << endl << endl;
The compiler can't know how to print your object. You have to provide a function for this.
You could
struct Item {
string name; //Item name.
int slot; //Head, Torso, Hands
int attack;
int knowledge;
int defense;
int hp;
int speed;
int charisma;
};
std::ostream &operator<<(std::ostream &os, const Item& item) {
os << item.name;
return os;
}
You have to overload operators for your classes if you want to use them.

C++ Error (operand types are 'std::string and 'void')

1st of all Im newBee at C++ programming.so please apologize if i make lots of mistake while asking questions.
My problem is:
i create class which contain private variable and Methods like below:
class Records{
private:
string name;
public:
string n;
void setValue(){
cout << "Enter name" << endl;
cin >> name;
}
void getValue(){
n = name;
cout << "Name is: " << n << endl;
}
};
I have run your code on GCC compiler, it's successfully worked. Please, see complete example :
#include <iostream>
using namespace std;
class Records{
private:
string name;
public:
string n;
void setValue(){
cout << "Enter name" << endl;
cin >> name;
}
void getValue(){
n = name;
cout << "Name is: " << n << endl;
}
};
int main()
{
Records r;
r.setValue();
r.getValue();
}

Class Header , string does not name a type

Hi I'm trying to finish my homework. I have a compilation error when I try to separate a class, then call it later. But the whole test function works properly. It has the class within the whole text. Basically when i try to separate the class from the text, I have an error message.
#include <iostream>
#include<string>
using namespace std;
class Person
{
private:
string alpha;
int beta;
public:
Person(string Name, int Age)
{
alpha = Name;
beta = Age;
}
string getName()
{
return alpha;
}
int getAge()
{
if (beta < 0)
{ beta = 0;
cout << "Error. A negative age cannot be entered. " << endl;
}
if (beta > 120)
{
cout << "Damn you're old. How many heart transplants have you had? You Vampire " << endl;
}
return beta;
}
void setName(string alpha)
{
}
void setAge(int beta);
void display();
};
int main()
{
Person Lu("Jess ", 22);
Person Rose("Gary ", 49);
cout << Lu.getAge() << " " << Lu.getName() <<endl;
cout << Rose.getAge() << " " << Rose.getName() << endl;
return 0;
}`
But when i separate the class,:
#include <iostream>
#include <string>
class Person
{
private:
string alpha;
int beta;
public:
Person(string Name, int Age)
{
alpha = Name;
beta = Age;
}
string getName()
{
return alpha;
}
int getAge()
{
if (beta < 0)
{ beta = 0;
cout << "Error. A negative age cannot be entered. " << endl;
}
if (beta > 120)
{
cout << "Damn you're old. How many heart transplants have you had? You Vampire " << endl;
}
return beta;
}
void setName(string alpha)
{
}
void setAge(int beta);
void display();
};
Main file
#include <iostream>
#include "Person.h"
#include <string>
using namespace std;
int main()
{
Person Lu("Jess ", 22);
cout << Lu.getAge() << " " << Lu.getName() <<endl;
return 0;
}`
But when I separate the class i get an error in codeblocks. Please help.
You forgot to put using namespace std; in Person.h.
Also, you don't have any header guards on Person.h, which won't cause a problem in such a simple program, but will as soon as multiple files include Person.h.

C++ class multiple inheritance error

I have been working on multiple inheritance. I have made a program but it keeps giving me an error such as Human::getInfo is ambiguous. How do I solve the problem
here is my code
#include <iostream>
#include <string>
using namespace std;
class Man{
protected:
std::string name;
public:
void getInfo(string hName){
name = hName;
}
void showInfo(){
std::cout << "Your name is: " << name << std::endl;
std::cout << "And you are a MAN" << std::endl;
}
};
class Women:public Man{
public:
Women(){}
void Women_showInfo(){
std::cout << "Your name is: " << name << std::endl;
std::cout << "And you are a Women" << std::endl;
}
};
class Human:public Women, public Man{
public:
Human(){}
};
int main(){
//local variables
string choice;
string name;
//class object
Human person;
//user interface
cout << "What your name: " ;
cin >> name;
cout << "Are you a [boy/girl]: ";
cin >> choice;
//saving name
person.getInfo(name); //ambiguous
//if handler
if (choice == "boy"){
person.showInfo(); //ambiguous
}else if(choice == "girl"){
person.Women_showInfo(); //works fine no error
}
system("pause");
return 0;
}
Also feel free to make changes in my code and would be even better if your could point out my mistake using my code.
Your design is rather questionable, but the particular ambiguity arises because Human inherits from both Woman and Man, but Woman already inherits from Man.
So Human has two getinfo() functions in it - Human::Man::getinfo() and Human::Woman::Man::getinfo(). Unless you tell the compiler which one to use it doesn't know, and thus reports an error.