I have just recently started class inheritance in c++. While I was making a "Test" program, a error occurred with the cout statement. No clue how to fix it and would be appreciate your response.
#include <iostream>
using namespace std;
class Power{
public:
void isWeak(){
cout << " Weak"<< endl;
}
void isStrong(){
cout << " Strong" << endl;
}
};
class Person:public Power{};
class Person2:public Power{};
int main(){
Person human;
Person2 human2;
cout << "Human is " << human.isWeak() << endl; //error
cout << "Human 2 is " << human2.isStrong() << endl; //error
system("pause");
return 0;
}
the main()'s cout statement has that error between the output and human
Change the functions to
char const *isWeak(){
return " Weak";
}
char const *isStrong(){
return " Strong";
}
As currently defined, both functions have void return type, which means the cout statements within main are trying to print void, which doesn't make sense, and is the cause of the error.
You are attempting to print a void:
cout << "Human is " << human.isWeak() << endl;
is the same as typing
cout << "Human is " << void << endl;
Which will not compile. What you need to do is define your functions in either of the following ways:
class Power
{
public:
std::string isWeak()
{
return std::string(" is weak");
}
std::string isStrong()
{
return std::string(" is strong");
}
};
Or, change your code:
cout << "Human is ";
human.isWeak();
cout << endl;
cout << "Human 2 is ";
human2.isStrong();
cout << endl;
Problem is with isWeak() and isStrong() return type. these two functions return void and you are trying to print it. you can try this-
cout << "Human is " ;
human.isWeak();
cout << endl;
cout << "Human 2 is " ;
human2.isStrong();
cout << endl;
You're trying to 'print' a 'void' statement in cout << "Human is " << human.isWeak() << endl;
You'll need to change your isWeak and isStrong functions to return a std::string/const char* or change the way you call them:
to string:
const char* isWeak() {
return " Weak";
}
// then you can do
cout << "Human is " << human.isWeak() << endl;
Or change the way you call the function:
cout << "Human is ";
human.isWeak();
Your isWeak and isStrong functions are void they do not return anything; calling cout << human.isWeak() is expecting isWeak to return something (an int, string, double, etc.).
Related
I'm starting learning to code in C++ (coming from VB.net) and i need some help in enum class usage.
I've done this simple code from a lerning exercise (originally divided in header.h and Exercise.cpp, but i putted it all together here):
#include <iostream>
#include <string>
#define BEGIN_WITH(x) { \
auto &_ = x;
#define END_WITH() }
using namespace std;
enum class Gender { Male, Female };
struct PersonStruct {
string _Name;
string _SurName;
int _Age;
double _Heigth;
Gender _Gender; };
class Person { public:
string _Name{};
string _SurName{};
int _Age{};
double _Heigth{};
Gender _Gender{}; };
int ModifyPerson(Person& PassPersona, PersonStruct Attribute) {
PassPersona._Name = Attribute._Name;
PassPersona._SurName = Attribute._SurName;
PassPersona._Heigth = Attribute._Heigth;
PassPersona._Age = Attribute._Age;
PassPersona._Gender = Attribute._Gender;
return(0); }
int main() { Person TestingPerson;
BEGIN_WITH(TestingPerson)
_._Age = 23;
_._Gender = Gender::Male;
_._Heigth = 1.94;
_._Name = "John";
_._SurName = "Smith";
END_WITH()
cout << "Person attributes: " << endl;
cout << "Name: " << TestingPerson._Name << endl;
cout << "Surname: " << TestingPerson._SurName << endl;
cout << "Age: " << TestingPerson._Age << endl;
cout << "Gender: " << TestingPerson._Gender << endl;
cout << "Heigth: " << TestingPerson._Heigth << endl;
cout << endl;
ModifyPerson(TestingPerson, PersonStruct{ "Poca","Hontas",24,1.85,Gender::Female });
cout << "New Person attributes: " << endl;
cout << "Name: " << TestingPerson._Name << endl;
cout << "Surname: " << TestingPerson._SurName << endl;
cout << "Age: " << TestingPerson._Age << endl;
cout << "Gender: " << TestingPerson._Gender << endl;
cout << "Heigth: " << TestingPerson._Heigth << endl;
return(0); }
I've made the structure in order to group all Person class parameters. Doing this i've learned that using enum class is more secure than class. But when i switched to enum class a lot of errors prompted on my code. I've solved almost all of them, except this:
cout << "Gender: " << TestingPerson._Gender << endl;
Error code E0349 "no operator "<<" matches these operands"
I've searched around but i find no solution to this. Thanks in advance for your time! (any suggestion or recommendation on my code should be appreciated)
<< operator is not defined for class Gender because it's your own class. You'll need to overload it. More info here.
enum class Gender
{
male,
female
};
ostream& operator<< (ostream & os, const Gender & g)
{
switch(g)
{
case Gender::male: os << "Male"; return os;
case Gender::female: os << "Female"; return os;
}
return os;
};
I've recently started learning c++ and for the life of me, I can't seem to get the syntax of using ostream in a class and what arguments should I pass. Here's the code:
This is the class in question:
#include <iostream>
#include <string>
using namespace std;
class Pokemon{
friend ostream& operator<<(ostream&, Pokemon);
public:
string name, level, cp;
Pokemon(string x="Pikachu", string y="5", string z="1000"){
name = x;
level = y;
cp = z;
}
Pokemon name(){
return this->name;
}
Pokemon level(){
return this->level;
}
Pokemon cp(){
return this->cp;
}
Pokemon display_stats(){
cout << this-> name << "stats are:" << endl;
cout << " " << "Attack: 2716.05" << endl;
cout << " " << "Defence: 1629.63" << endl;
cout << " " << "HP: 1086.42" << endl;
}
};
template<typename TYPE> //i dont understand this and the things i've written down here are only based on samples i've seen
ostream& operator<<(ostream& os, Pokemon & c){
os << "The level of " << c.name << " is" << c.level << " with cp of " << c.cp;
}
As you could see, I already tried constructing the ostream thing but I don't really understand how it works. This is my main function:
int main()
{
Pokemon a, b, c, d;
a = Pokemon();
b = Pokemon("Weezing");
c = Pokemon("Nidoking", 100);
d = Pokemon("Mewtwo", 50, 5432.1);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << "Jessie: You are no match to me! Go " << b.name << "!" << endl;
cout << "Gary: Go lvl " << c.level << " " << c.name << "! Crush them" << endl;
cout << "Ash: " << a.name << " can do it even thouh he is only level " << a.level << endl;
cout << "Jessie: Hahaha! My " << b.name << " CP is " << b.cp << endl;
cout << "Gary: "<< c.name << " CP is " << c.cp << endl;
cout << "Ash: " << a.name << " CP is " << a.cp << endl;
cout << "Giovanni: Behold " << d.name << " is here." << endl;
d.display_stats();
return 0;
}
I'm getting errors of:
no instance of constructor "Pokemon::Pokemon" matches the argument list -- argument types are: (const char [9], int) //on line c = Pokemon("Nidoking", 100);
no instance of constructor "Pokemon::Pokemon" matches the argument list -- argument types are: (const char [7], int, double) //on line d = Pokemon("Mewtwo", 50, 5432.1);
All of your Pokemon class methods are returning the wrong type. And your main() is not calling any of the methods correctly at all.
Change your Pokemon class to look more like this:
#include <iostream>
#include <string>
using namespace std;
class Pokemon {
private:
string m_name;
int m_level;
double m_cp;
friend ostream& operator<<(ostream&, const Pokemon&);
public:
Pokemon(string x="Pikachu", int y=5, double z=1000) {
m_name = x;
m_level = y;
m_cp = z;
}
string name() const {
return m_name;
}
int level() const {
return m_level;
}
double cp() const {
return m_cp;
}
void display_stats() const {
cout << m_name << " stats are:" << endl;
cout << " " << "Attack: 2716.05" << endl;
cout << " " << "Defense: 1629.63" << endl;
cout << " " << "HP: 1086.42" << endl;
}
};
ostream& operator<<(ostream& os, const Pokemon &c) {
os << "The level of " << c.m_name << " is " << c.m_level << " with cp of " << c.m_cp;
return os;
}
And then change main() to look more like this:
int main()
{
Pokemon a;
Pokemon b("Weezing");
Pokemon c("Nidoking", 100);
Pokemon d("Mewtwo", 50, 5432.1);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << "Jessie: You are no match to me! Go " << b.name() << "!" << endl;
cout << "Gary: Go lvl " << c.level() << " " << c.name() << "! Crush them" << endl;
cout << "Ash: " << a.name() << " can do it even though he is only level " << a.level() << endl;
cout << "Jessie: Hahaha! My " << b.name() << " CP is " << b.cp() << endl;
cout << "Gary: " << c.name() << " CP is " << c.cp() << endl;
cout << "Ash: " << a.name() << " CP is " << a.cp() << endl;
cout << "Giovanni: Behold " << d.name() << " is here." << endl;
d.display_stats();
return 0;
}
Live Demo
I have encountered a problem while running this code in my IDE. You can see very early on that I've attempted to use a function. The reason for this is to save memory later on by outputting text, but the problem occurs with the variables in the function. The classType variable is uninitialized, how do I prevent this? I have defined them in main, but when I try to output the text with the variables from main then it doesn't work properly.
#include<iostream>
using namespace std;
string getName()
{
string charName;
int classType;
cout << "What is your " << classType << "'s name?" << endl;
cin >> charName;
return charName;
}
int main()
{
int classType; //Later we will ask the user what class they're playing.
string charName;
/*We will use a function to ask a question.
We use a function to save memory instead of copy-pasting the text*/
cout <<"Welcome to \"Orcs and Ogres\"" << endl;
cout << "What class do you want to play? " << endl;
cout << "\tType 1 for Warrior class]" << endl;
cout << "\tType 2 for Archer class ]" << endl;
cout << "\tType 3 for Mage class ]" << endl;
cin >> classType;
if(classType == 1)
{
cout << endl << "You are a warrior" << endl;
string classType;
classType = "warrior";
getName();
}
else if(classType == 2)
{
cout << endl << "You are an archer" << endl;
string classType;
classType = "archer";
getName();
}
else if(classType == 3)
{
cout << endl << "You are a mage" << endl;
string classType;
classType = "mage";
getName();
}
else
{
cout << endl << "UserError: Number too high or too low";
}
}
On the lines of code that use getName(), it outputs something like "What is your blank's name?" instead of the proper classType. I want to know how I can send variable values to a function from main so that it outputs text properly here.
The reason why it's not working is because your getName function has no knowledge of whats stored in the classType variable. Read on how function variable scope works to understand the whole mechanism works might be beneficial.
If you wish to keep the current implementation of your program. Re-write your getName function to accept the string class as a parameter
string getName(string classType)
{
string charName;
cout << "What is your " << classType << "'s name?" << endl;
cin >> charName;
return charName;
}
and in your main you'd call the function as follow :
getName("Warrior"); // to ask warrior for a warriors' name
getName("Mage"); // to ask for a mage's name.
You may also want to add to include the string library at the top of your file as not having it might also cause your code to simply not work. As well as making sure to properly store the name returned from your getName() function as follow :
string name = getName("Warrior");
Also , as others have said , maybe reading a bit more on how function receive and return values might be beneficial to you.
It is as simple as this. Try this updated code...
#include<iostream>
using namespace std;
string getName(string classType)
{
string charName;
cout << "What is your " << classType << "'s name?" << endl;
cin >> charName;
cout<<"your "<<classType<< "'s name is "<<charName<<endl;
return charName;
}
int main()
{
int Type;
string charName;
cout <<"Welcome to \"Orcs and Ogres\"" << endl;
cout << "What class do you want to play? " << endl;
cout << "\tType 1 for Warrior class]" << endl;
cout << "\tType 2 for Archer class ]" << endl;
cout << "\tType 3 for Mage class ]" << endl;
cin >> Type;
if(Type == 1)
{
cout << endl << "You are a warrior" << endl;
string classType;
classType = "warrior";
getName("warrior");
}
else if(Type == 2)
{
cout << endl << "You are an archer" << endl;
string classType;
classType = "archer";
getName("archer");
}
else if(Type == 3)
{
cout << endl << "You are a mage" << endl;
string classType;
classType = "mage";
getName("mage");
}
else
{
cout << endl << "UserError: Number too high or too low";
}
return 0;
}
So here I have a class definition of a Car and then I create a carObject with it. I want the user to input values for all the variables in the carObject. As you see here, I have managed to get user input, but my approach to this problem is inefficient in my opinion.
I notice that all of the user inputs, except for the first one are very similar. I would like to use a loop of some kind to iterate over the declaration statements, or blocks of statements, and change the variable every time. I would like to put an if statement to enter different input only for the first iteration of the loop. I know that in bash I could use a string variable to stand for the variable name, but I don't know if that's possible in C++.
Notice that the object name does not change, but only the variables that are associated with it. I also use the same word for the user input, which preferably should be changed every iteration. I also have a series of arrays which are named similarly. The purpose of these arrays is to tell the user what options are available for a particular variable.
Although I have previous programming experience, I am relatively new to C++. A block of code that would serve as a solution to my problem that involves a call to another function would suit my purposes. Here is my code below.
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string Name;
string Model;
string Color;
string Transmission;
string Category;
};
int main() {
Car CarObject;
string modelOptions [3] = { "Ferrari", "Porsche", "Nissan" };
string colorOptions [4] = { "Blue", "Red", "Green", "White" };
string transmisionOptions [2] = { "Automatic", "Manual" };
string categoryOptions [3] = { "A", "B", "C" };
cout << "Enter " << "name" << " for Car 1." << endl;
cin >> carObject.Name;
cout << endl;
cout << "Enter " << "model" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: modelOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Model;
cout << endl;
cout << "Enter " << "color" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: colorOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Color;
cout << endl;
cout << "Enter " << "transmission" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: transmissionOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Transmission;
cout << endl;
cout << "Enter " << "category" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: categoryOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Category;
cout << endl;
...
return 0;
}
void Car::InputParameter(string& param, const string &msg, const vector<string>& options)
{
cout << msg << endl;
for (const string &text: options) {
cout << " " << text;
}
cout << "." << endl;
cin >> param;
cout << endl;
}
I think you might want something like this. You just call it for each member.
This block of code:
cout << "Enter " << "category" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: categoryOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Category;
cout << endl;
… can be replaced with a call to a function like this:
carObject.Category = userInput( "category", categoryOptions );
Clearly it returns a string (that is, a std::string).
The options argument should better be made a vector<string>.
Then just replace the other similar blocks with ditto calls to that function.
Is it a good idea to make that function a member function of Car?
No.
Consider, for example, how to then use Car in a GUI program (Graphical User Interface).
I have to create a method, which prints all collected data's on screen, here is my try:
bool UnPackedFood::printer() {
cout << " -- Unpacked Products --" << endl;
cout << "barcode: " << getBarcode() << endl;
cout << "product name: " << getBezeichnung() << endl << endl;
cout << "weight: " << getGewicht() << endl;
cout << "price" << getKilopreis() << endl;
return true;
}
In my main:
UnPackedFood upf;
cout << upf.printer();
This shows me the correct output, but it still delivers me a bool value back, which I actually dont need. I tried to declare the method as void, but thats not working.
You should overload << operator for output stream. Then when you type cout << upf it will print your product.
Take a look at this example and try to do something similar to following snippet:
class UnPackedFood {
...
public:
...
friend ostream & operator<< (ostream &out, const UnPackedFood &p);
};
ostream & operator<< (ostream &out, const UnPackedFood &p) {
out << " -- Unpacked Products --" << endl;
out << "barcode: " << p.getBarcode() << endl;
out << "product name: " << p.getBezeichnung() << endl << endl;
out << "weight: " << p.getGewicht() << endl;
out << "price" << p.getKilopreis() << endl;
return out;
}
Three possible solutions:
Don't do cout << upf.printer();, the output is not needed since the function itself does the output.
Instead of writing to the output in the printer function, append to a string and return the string.
Make an overloaded operator<< for UnPackedFood, so you can just do std::cout << upf;