Here is the problem:
In console.cpp
void Console::PrintMedicine(Medicine* m){
int ID = Medicine.getID(); //here i get the error expecting primary expression before "." token, it doesn't work with -> either
cout<<"The Medicine's ID is: ";
cin>>ID;
}
class Medicine:
what's private:
private:
int ID;
std::string nume;
double concentratie;
int cantitate;
what's public
public:
Medicine(); //implcit constructor
Medicine(int ID, std::string nume, double concentratie, int cantitate);//constructor with parameteres
~Medicine(); //destructor
//the getID function
const int& Medicine::getID() const{
return this->ID;
}
//the getName function
const std::string& Medicine::getName() const{
return this->nume;
}
//the getConcentration function
const double& Medicine::getConcentration() const{
return this->concentratie;
}
//the getQuantity function
const int& Medicine::getQuantity() const{
return this->cantitate;
}
The expression Medicine.getID() is incorrect. Medicine is the name of a class, and you can't use the dot operator to access its members. First, you need an instance of Medicine whose members you want to access; second, if you have a pointer to that instance, you need to use the arrow operator (operator ->).
Therefore, it should be:
void Console::PrintMedicine(Medicine* m){
int ID = m->getID();
// ^^^
// ...
}
Related
For example, I have this class:
struct bankingFunctionality
{
private:
class bankingData
{
public:
int phoneNum, citizenNum, age, ID;
string name, address;
bankingData* next = nullptr;
};
public:
void input(bankingData*);
void firstUser();
void update(bankingData*);
};
Is it ideal to put the data class in private to "protect" data? Since the only way, I can think of how to access it for input and output is to have functions like void input(...) in public. However, every time I want to call input I would need to create a new object and waste memory.
If you're using this as a way to pass in arguments it's really wasteful and you should consider the traditional getX() and setX() approach for accessors and mutators. You can make these easy to use in a chain style if you return *this at the end of each.
As in:
class bankingData {
int phoneNum, citizenNum, age, ID;
string name, address;
bankingData* next = nullptr;
int getPhoneNum() const { return phoneNum; };
bankingData& setPhoneNum(int n) { phoneNum = n; return *this; };
const std::string& getName() const { return name; };
bankingData& setName(const std::string& n) { name = n; return *this; };
};
Where you can then do:
bankingData bd;
bd.setPhoneNum(111).setName(...);
How can I copy all the objects to another set of objects. I created a temporary object so I can add the current "robot" to the "robotSquad". I am trying to dynamically add it
I am new to the concept of operator overloading, I might have the wrong assumption on what I'm doing. Im using the += operator, making a temp if there is no space in "robotSquad" adding it to temp then copying it to the original robotSquad named r_robot.
I could possibly be doing all this wrong, need help Thanks!
RobotSquad& RobotSquad::operator+=(const Robot& p_robot) {
if (count <= sizeof(r_robots)) {
//how do i copy?
RobotSquad temp[count+1];
temp[count]=p_robot;
for(int i=0 ;i<=sizeof(r_robots);i++){
temp[i]=r_robots[i];
}
} else {
this ->r_robots[count]=p_robot;
}
count++;
return *this;
}
class RobotSquad {
char* name ;
Robot *r_robots;
int count;
public:
//constructor
RobotSquad();
RobotSquad(Robot* , int, char* p_name= "No name");
~RobotSquad();
//getters
char* getName();
Robot* getRoster();
int getCount();
//setters
char setName();
Robot setRobot();
int setCount();
//other
RobotSquad& operator+=(const Robot&);
private:
void setEmpty();
};
With std, it could be:
class RobotSquad {
std::vector<Robot> robots;
std::string name;
public:
//constructor
RobotSquad() = default;
explicit RobotSquad(const std::vector<Robot>& robots,
const std::string& name= "No name")
: robots{robots}, name{name}
{}
~RobotSquad() = default;
RobotSquad& operator+=(const Robot& robot)
{
robots.push_back(robot);
return *this;
}
// ...
};
class Player
{
private:
int score;
public:
Player(int number);
~Player();
int get_score() { return score; }
Player& operator--();
};
Player::Player(int number)
{
score = number;
}
Player::~Player()
{
}
//-----
//Please turn your attention to this function
//-----
Player& Player::operator--() {
score--;
return *this;
}
Hello all, in the above class, I have overloaded the post-decrement operator to decrease the 'score'. There are two sub classes derived from this class - Computer and Human. From my understanding, they should also have access to this function. However, when I try:
Computer comp_; Human player_;
comp--;
human--;
I get an error saying: 'neither of these classes define this operator or a conversion to a type accessible to the predefined operator'. I am not allowed to redefine this function within the sub classes.
It would really help if someone could help me figure out how to get this code working! <3
You're trying to use the post-decrement operator, but you've declared the pre-decrement operator!
To make this code work, either use pre-decrement comp--; => --comp;. Or switch to defining the post-decrement operator Player& operator--(); => Player& operator--(int);. See a working example here: ideone.
For more on what each decrement/increment operator looks like, see the cppreference page.
The post decrement operator should look like this:
T T::operator--(int); // Inside class definition
T operator++(T& a, int); // Outside class definition
and it's supposed to return a copy of the object like it looked before you decreased its value.
class Player
{
private:
int score;
public:
Player(int number);
virtual ~Player();
int get_score() { return score; }
template<typename T>
friend T& operator--(T& p) { // pre
--p.score;
return p;
}
};
Player::Player(int number) : score(number) {}
Player::~Player() {}
template<typename T>
T operator--(T& p, int) { // post
T save(p);
--p; // using pre
return save;
}
The problem comes from the fact that you only define pre-increment operator.
see https://en.cppreference.com/w/cpp/language/operator_incdec
The pre-increment returns a reference, however the post increment returns a value therefore if you need to retain the type of the object returned. I would define the post-increment as a template and use the implementation of the pre-increment.
namespace Game
{
class Player
{
private:
int score;
public:
Player(int number);
~Player();
int get_score() { return score; }
Player& operator--();
};
Player::Player(int number)
{
score = number;
}
Player::~Player()
{
}
Player& Player::operator--() {
score--;
return *this;
}
template <class T> T operator--(const T& a, int)
{
T save(a);
save--;
return save;
}
class Human : public Player
{
public:
Human(int player) :Player(player) {}
};
class Computer : public Player
{
public:
Computer(int player) :Player(player) {}
};
}
example
int main()
{
Game::Human h(2);
Game::Human h2 = h--;
}
So I was trying to program a target heart rate calculator in C++ and when I tried to build it, this error was returned. Just to let you know, I am instructed to separate the implementation and interface.
Here's the interface
#include <iostream>
#include <string>
class HeartRates
{
public:
// constructor initialize HeartRates
HeartRates( std::string, std::string, int, int, int );
// Setting each variable
void setFirstName( std::string );
void setLastName( std::string );
void setdobMonth( int );
void setdobDay( int );
void setdobYear( int );
void setCurrentYear( int );
std::string getFirstName() const;
std::string getLastName() const;
int getdobMonth() const;
int getdobDay() const;
int getdobYear() const;
int getCYear() const;
int getAge() const;
int getMaximumHeartRate() const;
int getTargetHeartRate() const;
private:
std::string firstName;
std::string lastName;
int dobMonth;
int dobDay;
int dobYear;
int currentYear;
};
And here's the implementation
#include <iostream>
#include <string>
#include "HeartRates.h"
using namespace std;
// constructor that initializes all the stuff
This is the line that is giving me this error: Out-of-line definition of 'HeartRates' does not match any declaration in 'HeartRates'
HeartRates::HeartRates( string first, string last, int M, int D, int Y, int cY )
{
setFirstName( first );
setLastName( last );
setdobMonth( M );
setdobDay( D );
setdobYear( Y );
setCurrentYear( cY );
}
Continue on with the code
// set functions
void HeartRates::setFirstName( string first )
{
firstName = first; // store the first name in the object
}
void HeartRates::setLastName( string last )
{
lastName = last; // store the last name in the object
}
void HeartRates::setdobMonth( int M )
{
dobMonth = M; // store the month of birth in the object
}
void HeartRates::setdobDay( int D )
{
dobDay = D; // store the day of birth in the object
}
void HeartRates::setdobYear( int Y )
{
dobYear = Y; // store the year of birth in the object
}
void HeartRates::setCurrentYear( int cY )
{
currentYear = cY;
}
// get functions
string HeartRates::getFirstName() const
{
return firstName; // return user's first name
}
string HeartRates::getLastName() const
{
return lastName; // return user's last name
}
int HeartRates::getdobMonth() const
{
return dobMonth;
}
int HeartRates::getdobDay() const
{
return dobDay;
}
int HeartRates::getdobYear() const
{
return dobYear;
}
int HeartRates::getCYear() const
{
return currentYear;
}
// Functions
int HeartRates::getAge() const
{
int age;
age = currentYear-dobYear;
return age;
}
int HeartRates::getMaximumHeartRate() const
{
int maxHeartRate;
maxHeartRate = 220 - getAge();
return maxHeartRate;
}
int HeartRates::getTargetHeartRate() const
{
int targetHeartRate;
targetHeartRate = getMaximumHeartRate() * 0.85;
return targetHeartRate;
}
Sorry for the formatting and copy and pasting everything. Newbie here, I just don't know which part of the code went wrong.
HeartRates( std::string, std::string, int, int, int );
2 strings and 3 int.
HeartRates::HeartRates( string first, string last, int M, int D, int Y, int cY )
2 strings and 4 int.
I had a similar issue today and my fix was slightly different, so I'll throw this here in case it ever helps anyone in the future. I had forward declared a class OUTSIDE of the appropriate namespace in the header, so my error looked something like this:
1. Type of 1st parameter of member declaration does not match definition
'const std::shared_ptr<MyClass> &' (aka 'const shared_ptr<MyClass> &') vs
'const std::shared_ptr<MyClass> &' (aka 'const shared_ptr<myNamespace::MyClass> &'))
The solution for me was to forward declare that class inside the namespace, rather than outside it.
Bad:
class MyClass;
namespace myNamespace {
}
Good:
namespace myNamespace {
class MyClass;
}
I'm creating a c++ program of a race.
I have the race class. Each race has a name, a distance and vector of results pointers(its a result for each participant).
The result class has a pointer to the participant and a time.
The class time has hours, minutes and seconds.
I want to sort the vector of results from the fastest time to the slowest, so to compare results I created the function bool operator <(Result& res2) const in the class result.
All the functions in the .h file are implemented, I'm just not showing them all.
I'm almost certain that the function sortResults is not right but the function operator< is giving me errors that I don't know how to solve. It gives me this error in all the if statements: Multiple markers at this line
- passing 'const Time' as 'this' argument of 'unsigned int Time::getHours()' discards qualifiers [-
fpermissive]
- Line breakpoint: race.cpp [line: 217]
- Invalid arguments ' Candidates are: unsigned int getHours() '
Can you tell me what I'm doing wrong?
.h file:
class Time
{
unsigned int hours;
unsigned int minutes;
unsigned int seconds;
public:
Time(unsigned int h, unsigned int m, unsigned int s, unsigned int ms);
Time();
unsigned int gethours();
unsigned int getMinuts();
unsigned int getSeconds();
string show();
};
class Participant {
string name;
unsigned int age;
string country;
public:
Participant(string n, unsigned int a, string c);
string getName();
string getCountry();
int getAge();
string show() const;
};
class Result {
Participant *part;
Time time;
public:
Result(Participant *p, Time t);
Participant *getParticipant() const;
Time getTime();
string show();
bool operator <(Result& res2) const;
};
class Race {
string name;
float distance;
vector<Result *> results;
public:
Race(string nm, float dist);
string getName();
void setName(string nm);
float getDistance();
vector<Result *> sortResults();
void addResult(Result *r);
string showRaceResults();
string show();
};
.cpp file:
bool Result::operator <(Result& res2) const {
if (time.gethours() < res2.getTime().gethours())
return true;
else {
if (time.gethours() > res2.getTime().gethours())
return false;
else {
if (time.getMinutes() < res2.getTime().getMinutes())
return true;
else {
if (time.getMinutes() > res2.getTime().getMinutes())
return false;
else {
if (time.getSeconds() < res2.getTime().getSeconds())
return true;
else {
return false;
}
}
}
}
}
}
vector<Result *> Race::sortResults() {
sort (results.begin(), results.end(), operator <);
return results;
}
You should declare and define Time::gethours() as constant member function.
class Time {
// ...
unsigned int gethours() const; // note the "const"
};
unsigned int Time::gethours() const { /* ... */ } // note the "const"
To sort vector<Result*>, you need to
Change Result::operator<() to take const Result& rather than Result& as parameter
Define a comparison function for Result* which looks like static bool cmpResultPtr(const Result* lhs, const Result* rhs) { return *lhs < *rhs; }
Call sort(results.begin(), results.end(), cmpResultPtr);
The function cmpResultPtr() could be defined in the .cpp file, before the definition of Race::sortResults().
You declare operator< to be const but Time::getHours, which it calls, doesn't have the same declaration. To the compiler, this means getHours could change the value of the time member which violates the constness of operator<.