Entry point is int main() so I try summon pwr.GetSalary to cout outside string "Salary" and double value, however program does not print out anything.
So it is base class.
class Employee
{
public:
std::string FirstName;
std::string LastName;
std::string Patronymic;
double Salary;
Employee() {};
explicit Employee(std::string FirstName, std::string LastName,
std::string Patronymic, double Salary)
: FirstName(FirstName), LastName(LastName),
Patronymic(Patronymic), Salary(Salary) {}
bool operator==(Employee other) const
{
if (this->FirstName == other.FirstName &&
this->LastName == other.LastName &&
this->Patronymic == other.Patronymic)
return true;
else
return false;
}
};
An daughter class that inherits base class... Here is wonderful method that shall count a salary and print it out...
class Papersworker : public Employee
{
private:
std::string FirstName;
std::string LastName;
std::string Patronymic;
double Salary;
public:
Papersworker() {};
using Employee::Employee;
const std::string Job = "Papersworker";
std::map<std::string, double> Coefficient =
{
{"Director", 4.2},
{"Papersworker", 1.2},
{"Guardian", 1.5},
{"Programmer", 2.5}
};
void ChangeCoefficient(std::string Job, double NewCoefficient)
{
Coefficient[Job] = NewCoefficient;
}
void ChangeNameSalary(std::string FirstName, std::string LastName, std::string Patronymic, double Salary)
{
this->FirstName = FirstName;
this->LastName = LastName;
this->Patronymic = Patronymic;
this->Salary = Salary;
}
void PrintPapersworker()
{
std::cout << "First name\t" << "Lastname\t" << "Patronymic\t" << "Salary\n" << this->FirstName << "\t\t" << this->LastName << "\t" << this->Patronymic << "\t" << this->Salary << "\n" << std::flush;
for (const auto& i : this->Coefficient)
{
std::cout << i.first << " = " << i.second << ";\t" << std::flush;
}
std::cout << "\n------------------------------------------------------------\n" << std::flush;
}
double GetSalary(double Salary, std::string Job)
{
return Salary * this->Coefficient[Job];
}
};
Wonderful int main()'s part.
int main()
{
Papersworker pwr;
double sr = 0.0;
std::cout << "\nEnter director's salary\t" << std::flush; std::cin >> sr;
std::cout << "\nSalary\t" << pwr.GetSalary(sr, "Director");
return 0;
}
If you see a some bad and need optimization don't mind to reply. ._. I do not understand what is going on there in matter of classes building tricks. https://pastebin.com/p7HXaX80
P. S. My homework forces to use private FirstName,LastName,Patronymic,salary...
P. S. S. However, I use Visual Studio 2022 Preview with newest C++ nowadays.
https://imgur.com/a/N8cDK3n
program does not print out anything
Your program(pastebin link you gave) compiles successfully and prints continuously if you change _getch() to getch() as can be seen here. But for some reason it goes on forever. Since the link that you gave have around 500 lines of code i didn't take a look as to why the condition is not breaking(or if the program has any undefined behavior). Maybe you can narrow down the problem and edit your question again.
Your code will not compile as sr variable is not defined.
Define double sr; before using it in main()'s statement std::cin >> sr; and (at least) the program will compile and interact with the user.
int main() {
Papersworker pwr;
std::cout << "\nEnter director's salary\t" << std::flush;
double sr; // <- your missed variable
std::cin >> sr;
std::cout << "\nSalary\t" << pwr.GetSalary(sr, "Director");
}
Program's prints with input 10:
Enter director's salary 10
Salary 42
All of the private members of Papersworker shadow the public members from Employee
class Papersworker : public Employee {
private:
std::string FirstName;
std::string LastName;
std::string Patronymic;
double Salary;
// ...
};
Try this: Compiler Explorer (Untested ’cause I’m in a rush right now, I’ll look at it when I come back)
Also, be careful with std::map::operator []
Related
// The function which i was required to make was to.string() in the class,Which i had no idea how to make.This is an odd function(not comparing with the math one.)which returns value in two different types of data types i.e(string,integer).The only thing stuck me was assigning a variable after making (string to.string()) function//The return value of function is something like
[age,first_name,last_name,standard](without the square brackets with the commmasin the output)
p.s=need a simpler function without using vector header.
#include <iostream>
#include <sstream>
using namespace std;
class Student{
public :
void set_age(int no){
age_no=no;
}
void set_standard(int no){
std_no=no;
}
void set_first_name(string identity){
name_letter=identity;
}
void set_last_name(string identity2){
last_name_letter = identity2;
}
int get_age(){
return age_num;
}
int get_standard(){
return std_no;
}
string get_first_name(){
return name_letter;
}
string get_last_name(){
return last_name_letter;
}
private :
int age_no;
int std_no;
string name_letter;
string last_name_letter;
};
int main() {
int age, standard;
string first_name, last_name;
cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
cout << st.get_age() << "\n";
cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
cout << st.get_standard() << "\n";
cout << "\n";
cout << st.to_string();
return 0;
}
If you want to create a string with the format age, first_name, last_name, standard then you could do something like
class Student
{
public:
...
std::string to_string() const;
...
};
std::string Student::to_string() const
{
return std::to_string(get_age()) + ", " +
get_first_name() + ", "
get_last_name() + ", "
std::to_string(get_standard());
}
As an aside, I would suggest making all of your getter functions const for example
int get_age() const;
This denotes that the method will not mutate or modify any of the values of the class's member variables.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Write a program to
-> create a class “employee” with data member as name, designation, and basic salary and gross salary.
-> Create member functions as function getdata to read and function showdata to display details.
-> Create sum() as friend function to calculate gross salary.
BS=basic_salary
gs = basic_salary + 0.5 * basic_salary + 0.9 * basic_salary;
There's something wrong in my code. The get_gs() function is always returning 0. What is my error?
I have made it run again after deleting the previous .exe too, asumming compiler error. But it remains the same.
#include <iostream>
using namespace std;
class employee
{
string name;
string designation;
double bs;
double gs;
public:
employee()
{
}
employee(string _name, string des, double _bs)
{
name = _name;
designation = des;
bs = _bs;
}
void set(string _name, string des, double _bs)
{
employee(_name, des, _bs);
}
double get_gs()
{
double gs;
gs=bs + (0.5 * bs) + (0.9 * bs);
return gs;
}
};
int main()
{
employee *e = new employee;
string name, desti;
double bs, gs;
cout << "Enter name destiny basic_salary " << endl;
cin >> name >> desti >> bs;
e->set(name, desti, bs);
gs=e->get_gs();
cout << "the Gross salary :" << gs << endl;
return 0;
}
Solution with comments in the code:
#include <iostream>
// using namespace std; // not a good practise
class employee {
std::string name;
std::string designation;
double bs;
// double gs; // wasn't used so remove it
public:
// initialize values like this, and pass strings as "const&":
employee(const std::string& _name, const std::string& des, double _bs) :
name(_name), designation(des), bs(_bs)
{}
employee() : employee("", "", 0) {} // delegate to first constructor
void set(const std::string& _name, const std::string des&, double _bs) {
// your old set() created a temporary employee that
// wasn't used for anything and then it was destroyed
name = _name;
designation = des;
bs = _bs;
}
// make member functions that does not change the state of "this" const
double get_gs() const { return bs + (0.5 * bs) + (0.9 * bs); }
};
int main() {
employee e; // no need for new, create it like any other variable
std::string name, desti;
double bs, gs;
std::cout << "Enter name destiny basic_salary\n";
std::cin >> name >> desti >> bs;
e.set(name, desti, bs);
gs = e.get_gs();
std::cout << "the Gross salary : " << gs << "\n";
}
In your set() method, calling employee(_name, des, _bs); creates a new temporary employee object that is then immediately discarded. It does not update the members of the employee object that set() is called on, like you are expecting. As such, the bs member is never being assigned a value.
Try this instead:
#include <iostream>
using namespace std;
class employee
{
string name;
string designation;
double bs;
public:
employee() : bs(0.0) { }
employee(string _name, string des, double _bs)
: name(_name), designation(des), bs(_bs)
{
}
void set(string _name, string des, double _bs)
{
name = _name;
designation = des;
bs = _bs;
}
double get_gs() const
{
return bs + (0.5 * bs) + (0.9 * bs);
}
};
int main()
{
employee e;
string name, desti;
double bs, gs;
cout << "Enter name destiny basic_salary " << endl;
cin >> name >> desti >> bs;
e.set(name, desti, bs);
gs = e.get_gs();
cout << "the Gross salary :" << gs << endl;
return 0;
}
Alternatively:
int main()
{
string name, desti;
double bs, gs;
cout << "Enter name destiny basic_salary " << endl;
cin >> name >> desti >> bs;
employee e(name, desti, bs);
gs = e.get_gs();
cout << "the Gross salary :" << gs << endl;
return 0;
}
I have multiple classes and each of them has their own methods. All of these methods perform the same task, as you can see in my code. The only unique thing is the values of the title, code and credit members that are defined inside the classes.
Is there a way to write this code such that a single set of methods can do the required tasks (using the specific values within the class that made the request to the method) for each and every class?
I'm a university student, and due to this I don't want to use inheritance since we haven't learned it yet.
class seng305
{
string title = "Software design and architecture", code = "SENG305";
int credit = 4;
public:
seng305();
~seng305();
string get_info();
string get_title();
int get_credit();
};
class comp219
{
string title = "Electronics in computer engineering", code = "COMP219";
int credit = 4;
public:
comp219();
~comp219();
string get_info();
string get_title();
int get_credit();
};
seng305::seng305()
{
cout << '\t' << "Created" << endl;
}
seng305::~seng305()
{
cout << '\t' << "Destroyed" << endl;
}
string seng305::get_info()
{
return (code + "-" + title);
}
string seng305::get_title()
{
return title;
}
int seng305::get_credit()
{
return credit;
}
//--------------------------------------------------
comp219::comp219()
{
cout << '\t' << "Created" << endl;
}
comp219::~comp219()
{
cout << '\t' << "Destroyed" << endl;
}
string comp219::get_info()
{
return (code + "-" + title);
}
string comp219::get_title()
{
return title;
}
int comp219::get_credit()
{
return credit;
}
As you can see, the get_info(), get_title(), and get_credit() methods do the same thing.
I would like for a single get_info(), get_title(), get_credit() to be able to do the task for each class.
There is no reason to use separate classes at all in this example. A single class will suffice, eg:
class course
{
string title, code;
int credit;
public:
course(const string &title, const string &code, int credit);
~course();
string get_info() const;
string get_title() const;
int get_credit() const;
};
course::course(const string &title, const string &code, int credit)
: title(title), code(code), credit(credit)
{
cout << '\t' << "Created" << endl;
}
course::~course()
{
cout << '\t' << "Destroyed" << endl;
}
string course::get_info() const
{
return (code + "-" + title);
}
string course::get_title() const
{
return title;
}
int course::get_credit() const
{
return credit;
}
Then, you simply create instances of your class as needed, eg:
course seng305("Software design and architecture", "SENG305", 4);
course comp219("Electronics in computer engineering", "COMP219", 4);
...
I know you said that you don't want to use inheritance, but that could be the next logical step, using the above code as a base:
class courseSeng305 : public course
{
public:
courseSeng305() : course("Software design and architecture", "SENG305", 4) {}
};
class courseComp219 : public course
{
public:
courseComp219() : course("Electronics in computer engineering", "COMP219", 4) {}
};
courseSeng305 seng305;
courseComp219 comp219;
...
I'm encountering an error that says:
Invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'void')
I understand there are some questions related to this error posted on StackOverflow but I need some help and explanations regarding this specific context on what this error means.
In the main() function, I create a student object called s1. The error happens in main() where I'm trying to get the results of his GPA using a method of the Student class called getResults(double gpa).
#include <iostream>
using namespace std;
class Human{
protected: string name;
protected: int age;
public: Human(){
name = "Unknown";
age = 5;
}
public:
Human(string name, int age){
this->name = name;
this->age = age;
}
string getName(){
return name;
}
int getAge(){
return age;
}
void setName(string name){
this->name = name;
}
void setAge(int age){
this->age = age;
}
};
class Student: public Human{
protected: string school;
protected: double gpa;
public:
Student(string name, int age, string school, double gpa) : Human(name, age){
this->school = school;
this->gpa = gpa;
}
double getGPA(){
return gpa;
}
string getSchool(){
return school;
}
void setGPA(double gpa){
this->gpa = gpa;
}
void setSchool(string school){
this->school = school;
}
void getResult(double gpa){
if (gpa < 3.0) {
cout << "You did well!";
} else {
cout << "Try harder next time";
}
}
};
int main() {
Student s1 ("John", 23, 'm', "University of Chicago", 3.4);
double s1GPA = s1.getGPA();
cout << s1.getResult(s1GPA) << endl;
return 0;
}
Currently, your getResults function has a void return type, which means it doesn't actually return anything. Because of this, do not try to cout the result of this function in your main.
Consider the following edit:
// Your result is printed within this function
s1.getResult(s1GPA);
// Print a new line if you wish
cout << endl;
Also, since your getResults doesn't really get anything, I'd suggest changing the name to something like printResults.
Note
Notice how in your getResult it doesn't return anything because it's a void. In this function, you're just outputting text to the console with cout:
// Notice that this function doesn't actually return anything
void getResult(double gpa){
if (gpa < 3.0) {
// Output this message to console
cout << "You did well!";
} else {
// Output this message to console
cout << "Try harder next time";
}
}
When you have the statement in your main, it's trying to cout nothing because getResult is a void:
cout << s1.getResult(s1GPA) << endl;
// ^^^^^^^^^^^^^^^^^^^
// This doesn't return anything for cout to output.
That is why you only need to call getResult instead of trying to cout it.
I have a project for a class and I'm not sure what type of array I should be using for this program. I have to make a stock market program where the user buys, sells and views stock listings and checks their account balance. There are two text files that contain the following data:
Leon1111 5000.00
Wise2222 10000.00
Woo3333 3000.00
White4444 7000.00
Head5555 4000.00
and
Apple AAPL 450.00
Boeing BA 75.50
Intel INTC 22.30
Rambus RMBS 5.55
Sirius SIRI 3.15
Skyworks SWKS 25.35
Xilinx XLNX 36.80
This is the code I've written so far:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ofstream outStream;
int option;
do
{
cout << "1) Check Stock Listings " << endl;
cout << "2) Buy Stock " << endl;
cout << "3) Sell Stock" << endl;
cout << "4) Check Account Balance " << endl;
cout << "5) Quit " << endl << endl;
cout << "Please select an option : ";
cin >> option;
cout << endl;
if (option == 1)
{
fstream CompaniesFile;
CompaniesFile.open("Companies.txt");
if (CompaniesFile.is_open())
{
string s;
while (getline(CompaniesFile, s, '\n'))
{
cout << s << endl;
}
}
CompaniesFile.close();
}
else if (option == 2)
{
}
else if (option == 3)
{
}
else if (option == 4)
{
fstream AccountFile;
AccountFile.open("Account.txt");
if (AccountFile.is_open())
{
string t;
while (getline(AccountFile, t))
{
cout << t << endl;
}
}
AccountFile.close();
}
else if (option == 5)
{
cout << "Program Terminated. Have a nice day!" << endl << endl;
}
else
{
cout << "Invalid Option entered" << endl;
}
}
while (option != 5);
return 0;
}
class cCompany
{
std::string myName;
std::string mySymbol;
double myPrice;
public:
cCompany( const std::string& name,
const std::string& symbol,
double price )
: myName( name ), mySymbol( symbol ), myPrice( price )
{}
};
std::vector< cCompany > vCompany;
class cAccount
{
std::string myName
double myBalance;
public:
cAccount( const std:string& name, double balance )
: myName( name ), myBalance( balance )
{}
};
std:vector< cAccount > vAccount;
...
std::string name;
std::string symbol;
double price;
while ( CompaniesFile.good() )
{
CompaniesFile >> name;
CompaniesFile >> symbol;
CompaniesFile >> price;
vCompany.push_back( cCompany( name, symbol, price ));
}
You are going to probably need a bit more than name and balance for an account holder, so if I had my druthers I would use a vector (or map) of a class for account holders. The account holder class would hold name, balance, and then a vector (or even better a map) of shares that the person holds and the number of shares. Something like:
class AccountHolder{
private:
std::string name_;
long long int balance_; //balance in cents
//to allow for something like buy("AAPL", 100);
// to be implemented as:
// void buy(std::string symbol, long int shares)
// {
// long int price = shares * sharePrice[symbol];
// if (balance_ >= price)
// {
// balance_ -= price;
// holdings_[symbol] += shares;
// } else
// throw(INSUFFICIENT_FUNDS);
// }
std::map<std::string, long long int> holdings_;
public:
...
};
For shares, I would use a map since you only need to know their name (and/or symbol) and the price. Maybe you can have the key be the symbol, and then the value to be price, and another map for symbol and full name. This way you can easily find the share prices: all you need to do is
std::cout << "price of a single share from " << fullName["AAPL"]
<< " is: " << sharePrice["AAPL"] << "\n";
Try to make your application more OO-like (Object Oriented). My suggestion is first you can create some data structures:
struct user { string name; double balance; }
struct stock { string name; double price; }
struct stockBought { string userName; string stockName; int share; }
then use something to save your data, for example,
list<user> users;
list<stock> stocks;
list<stockBought> stockBought;
then you should have a function to read from the two files
readUsersFromFile(users, fUsersFile);
readStocksFromFile(stocks, fStockFile);
then you should have a function to update the list
update(users, 3, 1, 4000.0); //update the users list: 3rd user, 1st column (5000.0 => 4000.0)
add(stockBought, "Leon1111", "AAPL", 1); //leon bought 1 share of AAPL
then you have to implement all the functions needed for the 5 options. Add more utility functions/classes as you move on.
Once you finish the 1st version. you can polish your code to make it run faster (adding index etc) or look better (better class).