C++ Error when declare Get Method const - c++

problem with const in C++...
MyVektor[i].getName().getFirstName() generates error: (see code below)
Error 1 error C2662: 'Name::getFirstName' : cannot convert 'this' pointer from 'const Name' to 'Name &' c:\users\betula\documents\visual studio 2012\projects\c++laboration_2\c++laboration_2\person_test.cpp 215 1 C++Laboration_2
and
3 IntelliSense: the object has type qualifiers that are not compatible with the member function
object type is: const Name c:\Users\Betula\Documents\Visual Studio 2012\Projects\C++Laboration_2\C++Laboration_2\Person_Test.cpp 215 17 C++Laboration_2
Vector and Method call from main in PersonTest...
vector<Person> MyPersons;
ShowPerson(MyVektor);
Method:
void ShowPerson(vector<Person> &MyVektor)
{
cout << endl << " List of people: " << endl << endl;
for( size_t i = 0; i < MyVektor.size(); i++)
{
cout << " " + MyVektor[i].getName().getFirstName() + " " + MyVektor[i].getName().getLastName() << endl;
//cout << " " + MyVektor[i].getAddress() + " " + MyVektor[i].getAddress()+ " " + MyVektor[i].getAddress() << endl;
cout <<" Social security number: " + MyVektor[i].getPersNr() << endl;
cout <<" Shoe size: " + to_string(MyVektor[i].getSkoNr()) << endl << endl;
}
}
all Getmethods are declare const i there class Person & Name
const Name Person::getName()
{
return my_name;
}
const string Name::getFirstName()
{
return firstName;
}
if i remove const declare in Class Person & Name everything works...
Any suggestions for a beginner...
/ Nimos

Replace const Name Person::getName() with Name Person::getName() const etc. to make the functions constant as opposed to the return variable.

Related

Compiler Error - 'class Item' has no member named 'a' Line 46

#include<iostream>
#include<string>
using namespace std;
class Item{
private:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
public:
Item(string t, string a, string u, int aC, double w, string d){
type = t;
abbrv = a;
uID = u;
aircraft = aC;
weight = w;
destination = d;
}
Item(){}
Item(Item & i){
type = i.type;
abbrv = i.abbrv;
uID = i.uID;
aircraft = i.aircraft;
weight = i.weight;
destination = i.destination;
}
void print(){
cout << "ULD: " << type << endl;
cout << "Abbreviation: " << abbrv << endl;
cout << "ULD-ID: " << uID << endl;
cout << "Aircraft: " << aircraft << endl;
cout << "Weight: " << weight << " Kilograms" << endl;
cout << "Destination: " << destination << endl;
}
friend void kilotopound(Item);
};
void kilotopound(Item I){
cout<<"Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}
bool operator == (Item &ab, Item &bc){
if((ab.a == bc.a) && (ab.u == bc.u)){
return true;
}
else{
return false;
}
}
int main(){
Item I ("Pallet", "PAG32597IB", "PAG", 737, 3321, "SEA");
I.print();
kilotopound(I);
cout << "\nCopy\n\n";
Item I2(I);
I.print();
kilotopound(I);
cout<<"\nSecond Object\n\n";
I2.print();
kilotopound(I2);
Item unit1 ("Pallet", "PAG32597IB", "PAG", 737, 3321, "SEA");
Item unit2(unit1),unit3(I);
if (unit1 == unit2)
cout << "\nUnit1 and Unit2 are the same \n";
else
cout << " \nUnit1 and Unit2 aren't the same \n";
if (unit2 == unit3)
cout << " \nUnit2 and Unit3 are the same\n";
else
cout << " \nUnit2 and Unit3 aren't the same\n";
return 0;
}
Hi! So the code above gives me the error 'class Item' has no member named 'a' at line 46, which is where to bool operator is. Can someone help me out with basically just trying to get the code to function and explain why I get the error even though I have the data made public?
I'm pretty lost at why this happens even if the abbreviations are already stated. Also I tried just using abbrv and uID but got an error that the data was private.
Thank you!
a is the parameter of Item's constructor Item(string t, string a, string u, int aC, double w, string d), not an "alias" of Item::abbrv. Constructors are functions, and the parameters of a function are only available inside the function body.
There is no "member alias" in C++, nor is there any concept of "properties" (like in C#). To provide read-only access to Item::abbrv, define a "getter" function for it:
// Public member function of class Item:
const string& getAbbrv() const {
return abbrv;
}

Error C2079: 'CharCreateobject' uses undefined class 'CharacterCreation' + error C2228: left of '.CharacterRace' must have class/struct/union [duplicate]

EDIT #1: Everything before editing the line
<< "Owner: " << (*wo._owner).getLoginName() << endl;
worked completely fine, or at least didn't throw errors on me.
So I have the following code (obviously there is a lot more that if requested I will post, just not sure if more is needed or that is ok):
class Workout
{
private:
int _workoutid; // the ID of this workout
User* _owner; // Who did this workout
float _distance; // in miles
int _duration; // in seconds
int _day, _month, _year; // date: MM/DD/YYYY
int _weight; // lb, on the date of workout
// private methods (if necessary)
public:
friend std::ostream& operator<< (ostream& out, Workout& wo)
{
out << "Workout ID: " << wo._workoutid << endl
<< "Owner: " << (*wo._owner).getLoginName() << endl
<< "Distance: " << wo._distance << endl
<< "Duration: " << wo._duration / 3600 << ":" << (wo._duration % 3600) / 60 << ":" << wo._duration % 60 << endl
<< "Date: " << wo._month << ":" << wo._day << ":" << wo._year << endl
<< "Weight: " << wo._weight << endl;
return out;
}
// Print workout id, owner’s username, distance
// duration (HH:MM:SS), date (MM:DD:YY) and weight of
// the workout
// and other public methods (mutators/setters, accessors/getters)
Workout(void);
Workout(int, User*, float, int, int, int, int, int);
virtual ~Workout(void);
float getDistance();
void setDistance(float);
};
Workout::Workout(void) : _workoutid(), _distance(), _duration(), _day(), _month(), _year(), _weight()
{
_owner = new User();
}
Workout::Workout(int id, User* user, float distance, int duration, int day, int month, int year, int weight) :
_workoutid(id), _distance(distance), _duration(duration), _day(day), _month(month), _year(year), _weight (weight), _owner(user)
{
}
Workout::~Workout(void)
{
delete [] _owner;
}
class User
{
private:
char* _firstname; // First name
char* _lastname; // Last name
char* _loginname; // Login name
char* _password; // password
Workout* _myWorkouts[50];// an array of pointers to workouts
int _numWorkouts; // Num. of workout logged
User* _buddies[10]; // Friends
int _numBuddies; // Num. of friends
// private methods (if necessary)
public:
friend std::ostream& operator<< (ostream& out, User& user)
{
out << "First Name: [" << user._firstname << "]" << endl
<< "Last Name: ["<< user._lastname << "]" << endl
<< "Login Name: [" << user._loginname << "]" << endl
<< "Number of Workouts: [" << user._numWorkouts << "]" << endl
<< "Number of Friends: [" << user._numBuddies << "]" << endl;
return out;
}
User(void);
User(const char*, const char*, const char*, const char*);
virtual ~User(void);
char* getPassword(void);
char* getLoginName(void);
char* getFirstName(void);
void addWorkout(Workout*);
Workout* getWorkout(int);
void addBuddy(User* buddy);
// and other public methods (mutators/setters, accessors/getters)
};
User::User(void) : _firstname(), _lastname(), _loginname(), _password(),
_myWorkouts(), _numWorkouts(), _buddies(), _numBuddies()
{
}
User::User(const char* first, const char* last, const char* login, const char* pass) : _myWorkouts(), _numWorkouts(), _buddies(), _numBuddies()
{
_firstname = new char[20];
_lastname = new char[20];
_loginname = new char[20];
_password = new char[20];
for (int i=0; i < 20; i++){
_firstname[i] = first[i];
_lastname[i] = last[i];
_loginname[i] = login[i];
_password[i] = pass[i];
}
}
User::~User(void)
{
delete [] _firstname;
delete [] _lastname;
delete [] _loginname;
delete [] _password;
for(int i=0;i<50;i++) delete _myWorkouts[i];
delete [] _myWorkouts;
for(int i=0;i<10;i++) delete _buddies[i];
delete [] _buddies;
//What about variables such as _numWorkouts and _numBuddies?
}
And I am getting the following errors:
Error 1 error C2027: use of undefined type 'User'
Error 2 error C2228: left of '.getLoginName' must have class/struct/union
The first error is because the operator<< method somehow doesn't want to recognize that the (*wo._owner) object of type User initialized (which it is!)
The second error, obviously must be related to the second one, but it doesn't improve my chances of realizing at all how to solve the problem.
If this is indeed the structure of your code then you're trying to use "User" before it's defined.
You can't do this.
Declare your output operator as friend if need be and define it after the definition of User is known.

C++ Passing Pointer To A Function

I have a problem passing a pointer to a function. Here is the code.
#include <iostream>
using namespace std;
int age = 14;
int weight = 66;
int SetAge(int &rAge);
int SetWeight(int *pWeight);
int main()
{
int &rAge = age;
int *pWeight = &weight;
cout << "I am " << rAge << " years old." << endl;
cout << "And I am " << *pWeight << " kg." << endl;
cout << "Next year I will be " << SetAge(rAge) << " years old." << endl;
cout << "And after a big meal I will be " << SetWeight(*pWeight);
cout << " kg." << endl;
return 0;
}
int SetAge(int &rAge)
{
rAge++;
return rAge;
}
int SetWeight(int *pWeight)
{
*pWeight++;
return *pWeight;
}
My compiler outputs this:
|| C:\Users\Ivan\Desktop\Exercise01.cpp: In function 'int main()':
Exercise01.cpp|20 col 65 error| invalid conversion from 'int' to 'int*' [-fpermissive]
|| cout << "And after a big meal I will be " << SetWeight(*pWeight);
|| ^
Exercise01.cpp|9 col 5 error| initializing argument 1 of 'int SetWeight(int*)' [-fpermissive]
|| int SetWeight(int *pWeight);
|| ^
PS: In real life I wouldnt use this but I got into it and I wanna get it working this way.
You shouldn't dereference the pointer. It should be:
cout << "And after a big meal I will be " << SetWeight(pWeight);
Also, in SetWeight(), you are incrementing the pointer instead of incrementing the value, it should be:
int SetWeight(int *pWeight)
{
(*pWeight)++;
return *pWeight;
}
int *pWeight = &weight;
This declares pWeight as a pointer to an int. SetWeight actually takes a pointer to an int, so you can just pass pWeight straight in without any other qualifiers:
cout << "And after a big meal I will be " << SetWeight(pWeight);
First I took your feedback and changed:
cout << "And after a big meal I will be " << SetWeight(*pWeight);
// to
cout << "And after a big meal I will be " << SetWeight(pWeight);
// But after that I changed also:
*pWeight++;
// to
*pWeight += 1;
The * symbol can have two different meanings in C++. When used in a function header, they indicate that the variable being passed is a pointer. When used elsewhere in front of a pointer it indicates that to which the pointer is pointing. It seems you may have confused these.

Cannot call member function std::string Sportist::getIme() without object

I have a class A:
class Sportist{
private:
string ime;
int godina_na_ragjanje;
int godisna_zarabotuvacka_EUR;
public:
Sportist(string i, int g_n_r, int g_z_EUR){
ime = i;
godina_na_ragjanje = g_n_r;
godisna_zarabotuvacka_EUR = g_z_EUR;
}
string getIme(){
return ime;
}
int getGodinaNaRagjanje(){
return godina_na_ragjanje;
}
int getGodisnaZarabotuvackaEUR(){
return godisna_zarabotuvacka_EUR;
}
};
And class B using the class A as public:
class Fudbaler:public Sportist{
private:
int broj_na_odigrani_natprevari;
int danocna_stapka;
public:
Fudbaler(string ime, int godina, int zarabotuvacka, int b, int d)
:Sportist(ime, godina, zarabotuvacka)
{
broj_na_odigrani_natprevari = b;
danocna_stapka = d;
}
float danok(){
return getGodisnaZarabotuvackaEUR() * danocna_stapka;
}
friend ostream& operator<<(ostream &os, Fudbaler F){
return os << "Ime: " << getIme() << endl
<< "Godina na raganje: " << getGodinaNaRagjanje() << endl
<< "Godisna zarabotuvacka(EUR): " << getGodisnaZarabotuvackaEUR() << endl
<< "Danok sto treba da plati: " << danok();
}
};
And I get 4 errors as described in title in these lines:
return os << "Ime: " << getIme() << endl
<< "Godina na raganje: " << getGodinaNaRagjanje() << endl
<< "Godisna zarabotuvacka(EUR): " << getGodisnaZarabotuvackaEUR() << endl
<< "Danok sto treba da plati: " << danok();
cannot call member function 'std::string Sportist::getIme()' without object
cannot call member function 'int Sportist::getGodinaNaRagjanje()' without object
cannot call member function 'int Sportist::getGodisnaZarabotuvackaEUR()' without object
cannot call member function 'float Fudbaler::danok()' without object
i would say the function should be changed to
friend ostream& operator<<(ostream &os, Fudbaler F){
return os << "Ime: " << F.getIme() << endl
<< "Godina na raganje: " << F.getGodinaNaRagjanje() << endl
<< "Godisna zarabotuvacka(EUR): " << F.getGodisnaZarabotuvackaEUR() << endl
<< "Danok sto treba da plati: " << F.danok();
}
I am not shure about operator overloading for the std::streams. i usually have done that outside of the class. From your error messages, you need to use the passed Fudbaler variable to access the methods of it.

Getting "Use of undefined type" and "Must have class/struct/union" errors

EDIT #1: Everything before editing the line
<< "Owner: " << (*wo._owner).getLoginName() << endl;
worked completely fine, or at least didn't throw errors on me.
So I have the following code (obviously there is a lot more that if requested I will post, just not sure if more is needed or that is ok):
class Workout
{
private:
int _workoutid; // the ID of this workout
User* _owner; // Who did this workout
float _distance; // in miles
int _duration; // in seconds
int _day, _month, _year; // date: MM/DD/YYYY
int _weight; // lb, on the date of workout
// private methods (if necessary)
public:
friend std::ostream& operator<< (ostream& out, Workout& wo)
{
out << "Workout ID: " << wo._workoutid << endl
<< "Owner: " << (*wo._owner).getLoginName() << endl
<< "Distance: " << wo._distance << endl
<< "Duration: " << wo._duration / 3600 << ":" << (wo._duration % 3600) / 60 << ":" << wo._duration % 60 << endl
<< "Date: " << wo._month << ":" << wo._day << ":" << wo._year << endl
<< "Weight: " << wo._weight << endl;
return out;
}
// Print workout id, owner’s username, distance
// duration (HH:MM:SS), date (MM:DD:YY) and weight of
// the workout
// and other public methods (mutators/setters, accessors/getters)
Workout(void);
Workout(int, User*, float, int, int, int, int, int);
virtual ~Workout(void);
float getDistance();
void setDistance(float);
};
Workout::Workout(void) : _workoutid(), _distance(), _duration(), _day(), _month(), _year(), _weight()
{
_owner = new User();
}
Workout::Workout(int id, User* user, float distance, int duration, int day, int month, int year, int weight) :
_workoutid(id), _distance(distance), _duration(duration), _day(day), _month(month), _year(year), _weight (weight), _owner(user)
{
}
Workout::~Workout(void)
{
delete [] _owner;
}
class User
{
private:
char* _firstname; // First name
char* _lastname; // Last name
char* _loginname; // Login name
char* _password; // password
Workout* _myWorkouts[50];// an array of pointers to workouts
int _numWorkouts; // Num. of workout logged
User* _buddies[10]; // Friends
int _numBuddies; // Num. of friends
// private methods (if necessary)
public:
friend std::ostream& operator<< (ostream& out, User& user)
{
out << "First Name: [" << user._firstname << "]" << endl
<< "Last Name: ["<< user._lastname << "]" << endl
<< "Login Name: [" << user._loginname << "]" << endl
<< "Number of Workouts: [" << user._numWorkouts << "]" << endl
<< "Number of Friends: [" << user._numBuddies << "]" << endl;
return out;
}
User(void);
User(const char*, const char*, const char*, const char*);
virtual ~User(void);
char* getPassword(void);
char* getLoginName(void);
char* getFirstName(void);
void addWorkout(Workout*);
Workout* getWorkout(int);
void addBuddy(User* buddy);
// and other public methods (mutators/setters, accessors/getters)
};
User::User(void) : _firstname(), _lastname(), _loginname(), _password(),
_myWorkouts(), _numWorkouts(), _buddies(), _numBuddies()
{
}
User::User(const char* first, const char* last, const char* login, const char* pass) : _myWorkouts(), _numWorkouts(), _buddies(), _numBuddies()
{
_firstname = new char[20];
_lastname = new char[20];
_loginname = new char[20];
_password = new char[20];
for (int i=0; i < 20; i++){
_firstname[i] = first[i];
_lastname[i] = last[i];
_loginname[i] = login[i];
_password[i] = pass[i];
}
}
User::~User(void)
{
delete [] _firstname;
delete [] _lastname;
delete [] _loginname;
delete [] _password;
for(int i=0;i<50;i++) delete _myWorkouts[i];
delete [] _myWorkouts;
for(int i=0;i<10;i++) delete _buddies[i];
delete [] _buddies;
//What about variables such as _numWorkouts and _numBuddies?
}
And I am getting the following errors:
Error 1 error C2027: use of undefined type 'User'
Error 2 error C2228: left of '.getLoginName' must have class/struct/union
The first error is because the operator<< method somehow doesn't want to recognize that the (*wo._owner) object of type User initialized (which it is!)
The second error, obviously must be related to the second one, but it doesn't improve my chances of realizing at all how to solve the problem.
If this is indeed the structure of your code then you're trying to use "User" before it's defined.
You can't do this.
Declare your output operator as friend if need be and define it after the definition of User is known.