#include <iostream>
using namespace std;
class DrivingLicence
{
protected:
Person owner;
char * type;
Date validity;
int id;
static int cid;
public:
DrivingLicence(Person &o,char* t,Date &d);
DrivingLicence(Person &o,char* t);
DrivingLicence(const DrivingLicence & other);
Date getValidity() const;
int checkValidity() const;
void print() const;
bool operator== (const DrivingLicence& o) const;
void operator +(const int num);
const DrivingLicence& operator= (const DrivingLicence& other);
~DrivingLicence();
};
class Person
{
private:
int id;
char* name;
Date birthday;
public:
Person(char* name,int id1,Date &d);
Person(const Person &other);
~Person();
Date getBirthday() const;
const Person& operator= (const Person & other);
void print() const;
};
class Date
{
int day;
int month;
int year;
public:
Date (int day,int month,int year);
~Date();
const Date& operator=(const Date& other);
bool operator==(const Date & other);
void print() const;
int getYear()const;
int getMonth()const;
int getDay()const;
};
up above are my classes,
i need to initialize both constructors in the DrivingLicence class (not the copy cons), however i cant manage to do that.
can someone please help me with the syntax for this question??
what i mean is :
#include <NameOfHeaderFile>
DrivingLicense::DrivingLicense( Person &o,char* t,Date &d ) : //Code here for 1stconstructor
{
}
DrivingLicense::DrivingLicense( Person &o,char* t ) ://Code here for 2nd constructor
{
}
i don't know how to initialize the values
I assume this is a header file, however usually there is only 1 class per .h file. So you need to create a file called DrivingLicence.cpp.
In this file write:
#include <NameOfHeaderFile>
DrivingLicense::DrivingLicense( Person &o,char* t,Date &d )
{
//Code here for 1stconstructor
}
DrivingLicense::DrivingLicense( Person &o,char* t )
{
//Code here for 2nd constructor
}
Is this what you are asking???
If I have understood your problem, you want a DriverLicence constructor that
also initializes the person inside the DriverLicense instance.
If so, you only have to add this overload to your class:
DriverLicense::DriverLicense(
// Data for Person
char *person_name, int person_id, Date day_birth,
// Data for Driver licence
char *t, Date d)
{
owner = Person(person_name, person_id, day_birth);
// More code here initializing DeriverLicence members.
}
Remember of course add it to your class:
class DriverLicence
{
public:
// ...
DriverLicense::DriverLicense(char *, int, Date, char *t, Date d);
// ...
}
A couple of Advice:
You're working with C++, use std:string instead char*
Don't abuse of passing arguments as references. Some times this is not
the best to do.
If you're trying to initialize the members of your DrivingLicense class with the arguments passed to the constructor, you can do that in your initializer list.
It's would be wise to put these definitions in a cpp. Also note the changes to types and constness or the arguments I'm providing.
DrivingLicense::DrivingLicense(const Person &o, const std::string& t, const Date &d )
: owner(o)
, type(t)
, validity(d)
{ }
DrivingLicense::DrivingLicense(const Person &o, const std::string& t)
: owner(o)
, type(t)
{ } // Note that 'validity' here is default constructed.
include "header.h"
int DrivingLicence::cid =1000;
DrivingLicence::DrivingLicence(Person &o, char* t, Date &d ): owner(o), type(t), validity(d)
{
}
DrivingLicence::DrivingLicence(Person &o,char* t) :owner(o), type(t),validity(8,10,2024){}
this is what i meant.
thanks for all the answers.
Related
I can compile normal,when I use vector:
TEST(function_obj,bindMemeber1){
std::vector<Person> v {234,234,1241,1241,213,124,152,421};
std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) );
}
but when I use set,something wrong:
TEST(function_obj,bindMemeber1){
std::set<Person,PersonCriterion> v{234,234,1241,1241,213,124,152,421};
std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) );
}
clion's tips
The IDE tell me that something wrong.when I force IDE to compile, it also can't compile successfully .
Below is the code of Person;
class Person{
private:
size_t no;
std::string name;
public:
Person():no(0){};
Person(size_t n): no(n){};
Person(const Person& p):no(p.no),name(p.name){};
friend class PersonCriterion;
size_t getNo() const;
void print(){
std::cout<<no<<' ';
}
const std::string &getName() const;
};
class PersonCriterion{
public:
bool operator()(const Person& p1,const Person& p2){
return p1.no<=p2.no;
}
};
size_t Person::getNo() const {
return no;
}
const std::string &Person::getName() const {
return name;
}
Elements got from std::set are const-qualified; they're supposed to be non-modifiable. You should mark Person::print as const then it could be called on a const object.
class Person {
...
void print() const {
// ^^^^^
std::cout<<no<<' ';
}
...
};
BTW: Better to mark operator() in PersonCriterion as const too.
class PersonCriterion {
public:
bool operator()(const Person& p1, const Person& p2) const {
return p1.no<=p2.no;
}
};
somehow I can't use stable_partition algorithm on
vector<pair<Class, string>>.
I can re-organize the code to get what I want, but for me (as I am new to C++) it's more "WHY" and not "HOW" question. will be glad if you clarify this behavior:
First, class Date (you can omit it and come look at it later):
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
class Date {
public:
Date(int new_year, int new_month, int new_day) {
year = new_year; month = new_month; day = new_day;
}
int GetYear() const {return year;}
int GetMonth() const {return month;}
int GetDay() const {return day;}
private:
int year, month, day;
};
bool operator<(const Date& lhs, const Date& rhs) {
return vector<int>{lhs.GetYear(), lhs.GetMonth(), lhs.GetDay()} <
vector<int>{rhs.GetYear(), rhs.GetMonth(), rhs.GetDay()};
}
bool operator==(const Date& lhs, const Date& rhs) {
return vector<int>{lhs.GetYear(), lhs.GetMonth(), lhs.GetDay()} ==
vector<int>{rhs.GetYear(), rhs.GetMonth(), rhs.GetDay()};
}
SO THIS IS THE CLASS WITH THE TROUBLE:
class Database {
public:
void Add(const Date& date, const string event){
storage.push_back(make_pair(date, event));
set_dates.insert(date);
}
void Print(ostream& s) const{
for(const auto& date : set_dates) {
// TROUBLE IS HERE:
auto it = stable_partition(begin(storage), end(storage),
[date](const pair<Date, string> p){
return p.first == date;
});
};
}
private:
vector<pair<Date, string>> storage;
set<Date> set_dates;
};
When compiled, it returns a lot of problems of same kind:
I've tried the same code on vector<pair<int, string>> (used stable_partition with lambda {return p.first == _int; } and it worked.
Would appreciate your help
The std::stable_partition function is supposed to modify the vector. However, you are calling it in a const member function, so storage is const there. This can't work.
Solution: Don't make Print const, or use std::stable_partition on a copy of storage. Neither is a great solution, so you should probably rethink your design.
You need to define overloading operator= for Date class as well. It will work if you do that stuff.
class Date {
public:
Date(int new_year, int new_month, int new_day) {
year = new_year; month = new_month; day = new_day;
}
// Need to define overloading operator=
Date& operator=(const Date& rhs)
{
}
int GetYear() const {return year;}
int GetMonth() const {return month;}
int GetDay() const {return day;}
private:
int year, month, day;
};
I'm working on a project where I have to write a class that contains three other classes as private member variables to a binary file, where it can then be read back into variables to be used in the code. The code writes to the file, but I don't know if it is writing the correct info as when I try to read the file it reads in junk. I have included my current setup, does this look correct? If so, what could be going wrong, and if not, how can I fix this?
If you need me to add any extra code, please ask. Another consideration is that two of the classes being used as member functions for the players objects inherit from other classes.
if (cFile.is_open())
{
cFile.seekp(ios::beg);
for (int i = 0; i < 3; i++)
{
cFile.write(reinterpret_cast<char *>(&players[i]), sizeof(Character));
}
cFile.seekg(ios::beg);
for (int i = 0; i < 3; i++)
{
cFile.read(reinterpret_cast<char *>(&playersRead[i]), sizeof(Character));
playersRead[i].display();
}
cFile.close();
}
else
{
cout << "Error opening file." << endl;
}
I've been working on this code for a few days and am really having trouble. I appreciate any help I can get, thanks in advance.
#pragma once
#include <iostream>
using std::ostream;
#include "string.h"
#include "coinPouch.h"
#include "backpack.h"
class Character
{
public:
Character();
Character(String name);
Character(String name, CoinPouch wallet, Backpack storage);
Character(const Character & copy);
~Character();
Character & operator =(const Character & rhs);
friend ostream & operator << (ostream & out, const Character & c);
void purchase(int p, int g, int s, int c);
void income(int p, int g, int s, int c);
void addPotion(const Potion & toAdd);
void checkBalance();
void checkBackpack();
void changeName(const String & newN);
void display();
String getName();
CoinPouch getWallet();
Backpack getStorage();
void setName(String name);
void setWallet(CoinPouch wallet);
void setStorage(Backpack storage);
private:
String m_name;
CoinPouch m_wallet;
Backpack m_storage;
};
#include "character.h"
using std::endl;
using std::cout;
Character::Character() : m_name("Player")
{
CoinPouch initialW;
Backpack initialS;
m_wallet = initialW;
m_storage = initialS;
}
Character::Character(String name) : m_name(name)
{
CoinPouch initialW;
Backpack initialS;
m_wallet = initialW;
m_storage = initialS;
}
Character::Character(String name, CoinPouch wallet, Backpack storage) : m_name(name), m_wallet(wallet), m_storage(storage)
{
}
Character::Character(const Character & copy) : m_name(copy.m_name), m_wallet(copy.m_wallet), m_storage(copy.m_storage)
{
}
Character::~Character()
{
}
Character & Character::operator =(const Character & rhs)
{
if (this != &rhs)
{
m_name = rhs.m_name;
m_wallet = rhs.m_wallet;
m_storage = rhs.m_storage;
}
return *this;
}
ostream & operator << (ostream & out, const Character & c)
{
out << c.m_name << ": " << endl;
out << c.m_wallet << endl;
out << c.m_storage << endl;
return out;
}
void Character::purchase(int p, int g, int s, int c)
{
m_wallet.buy(p, g, s, c);
}
void Character::income(int p, int g, int s, int c)
{
m_wallet.add(p, g, s, c);
}
void Character::addPotion(const Potion & toAdd)
{
m_storage.addPotion(toAdd);
}
void Character::checkBalance()
{
m_wallet.display();
}
void Character::checkBackpack()
{
m_storage.displayContents();
}
void Character::changeName(const String & newN)
{
m_name = newN;
}
void Character::display()
{
cout << m_name << ": " << endl;
m_wallet.display();
m_storage.displayContents();
}
String Character::getName()
{
return m_name;
}
CoinPouch Character::getWallet()
{
return m_wallet;
}
Backpack Character::getStorage()
{
return m_storage;
}
void Character::setName(String name)
{
m_name = name;
}
void Character::setWallet(CoinPouch wallet)
{
m_wallet = wallet;
}
void Character::setStorage(Backpack storage)
{
m_storage = storage;
}
#pragma once
#include <iostream>
using std::ostream;
#include "string.h"
class CoinPouch
{
public:
CoinPouch();
CoinPouch(String init);
CoinPouch(int p, int g, int s, int c);
CoinPouch(const CoinPouch & copy);
~CoinPouch();
CoinPouch & operator = (const CoinPouch & rhs);
friend ostream & operator << (ostream & out, const CoinPouch & c);
void add(int p, int g, int s, int c);
bool checkCost(int p, int g, int s, int c);
void buy(int p, int g, int s, int c);
void convertCost();
void roundUp();
void display();
int getP();
int getG();
int getS();
int getC();
private:
String m_amount;
int m_platinum;
int m_gold;
int m_silver;
int m_copper;
};
#pragma once
#include "potions.h"
class DynamicArray
{
public:
// Constructors
DynamicArray();
~DynamicArray();
DynamicArray(const DynamicArray & copy);
// Op Equals
DynamicArray & operator =(const DynamicArray & rhs);
// Insert, delete, and get elements functions
int getElements();
void Insert(const Potion & add);
void Delete(const Potion & rmv);
void display();
// Overloaded operators
Potion & operator [](int index);
friend ostream & operator << (ostream & out, const DynamicArray & d);
private:
// Member variables
Potion * m_array;
int m_elements;
// Find function
int Find(const Potion & target);
};
#pragma once
#include "string.h"
#include <iostream>
using std::ostream;
class Potion
{
public:
// Constructors
Potion();
Potion(String name, String description, String potency, String cost);
Potion & operator = (const Potion & rhs);
Potion(const Potion & copy);
// Desctructor
~Potion();
// Overloaded operators
bool operator == (const Potion & rhs) const;
friend ostream & operator << (ostream & out, const Potion & p);
// Getter functions
String getName();
String getDesc();
String getPotency();
String getCost();
int getP();
int getG();
int getS();
int getC();
// Setter functions
void setName(String name);
void setDesc(String desc);
void setPotency(String potency);
void setCost(String cost);
// Convert and display functions
void convertCost();
void display();
private:
// Strings to hold item information
String m_name;
String m_description;
String m_potency;
String m_cost;
// Ints to hold cost information
int m_platinum;
int m_gold;
int m_silver;
int m_copper;
// Logical test
bool m_isnull = false;
};
#pragma once
#include <iostream>
using std::ostream;
class String
{
public:
// Constructors
String();
String(char ch);
String(const char * str);
// Destructor
~String();
// Copy Constructor and Copy Assignment Constructor
String(const String & copy);
String & operator=(const String & rhs);
friend ostream & operator << (ostream & out, const String & s);
// Added Functionality
void display();
void upper();
void lower();
// Operator Conversion
operator char *();
operator const char *();
// Overloaded operator
bool operator == (const String & rhs) const;
private:
// Member variables
char * m_str;
int m_ischar;
};
#pragma once
#include "dynamicarray.h"
#include "coinPouch.h"
#include "string.h"
class Backpack
{
public:
Backpack();
Backpack(DynamicArray potions);
Backpack(const Backpack & copy);
~Backpack();
Backpack & operator = (const Backpack & rhs);
friend ostream & operator << (ostream & out, const Backpack & c);
void addPotion(const Potion & add);
void usePotion(const Potion & rm);
void displayContents();
private:
DynamicArray m_potions;
int m_number;
};
This is a school project, and I am supposed to write the Character class to a binary file in order to save the characters so I can load them in on the program start. Right now I'm just trying to make sure that they can be successfully written to and read from the binary file and I have had no luck.
My bad, didn't know what to post and I didn't want to post everything in my file. Here is the character class. Let me know what else is needed, if anything.
It should be immediately obvious that this code can't possibly work.
cFile.write(reinterpret_cast<char *>(&players[i]), sizeof(Character));
However big sizeof(Character) is, we could have a Character with an m_name that takes up more bytes than that. So this code can't possibly be writing the character's name, and it clearly needs to do that.
Before you write anything to a file, decide on (and ideally, document) a file format at the byte level. Make sure your code writes in the format you documented and also can read in the format you documented. Skipping this step leads to pain and it also makes debugging impossible because you can't look at the file and compare it to a specification to see whether the writer or the reader is at fault.
Had you documented what bytes the player's name will occupy in the file, you'd immediately realize that you either need to have a variable-length object and encode the length somehow or pick a largest size name and allocate those many bytes. But because you skipped that vital step, you never actually worked out how to write a Character to a file.
this is my first question so please bear with any formatting mistakes i make, I'll try to edit them :)
I've got this function which finds the max of three variables of some data type X and returns it.
template <class X>
X fmax(X a, X b, X c)
{
X temp=a;
if (b>temp)
temp=b;
if(c>temp)
temp=c;
return temp;
}
Then there is the class Person which looks like this
class Person
{
private:
char* name;
int height;
char gender;
public:
Person(){}
Person(char * name,int height, char gender)
{
int sz=strlen(name);
this->name= new char [sz];
strcpy(this->name,name);
this->height=height;
this->gender=gender;
}
void setName(char* name)
{
int sz=strlen(name);
this->name= new char [sz];
strcpy(this->name,name);
}
void setHeight(int h){this->height=h;}
void setGender(char g){this->gender=g;}
char* getName(){return this->name;}
int getHeight(){return this->height;}
char getGender(){return this->gender;}
Person operator= (Person p)
{
int sz=strlen(p.getName());
this->name= new char [sz];
strcpy(this->name,p.getName());
this->height=p.getHeight();
this->gender=p.getGender();
return *this;
}
bool operator> (Person p)
{
if(this->getHeight()>p.getHeight())//The persons should be compared using their heights.
return true;
return false;
}
};
and I also overloaded the ostream:
ostream &operator<<(ostream &mystream, Person &p)
{
mystream<<"The person's name is: "<<p.getName()<<endl;
mystream<<"The person's height is: "<<p.getHeight()<<endl;
mystream<<"The person's gender is: "<<p.getGender()<<endl;
return mystream;
}
But I'm getting the error in my main:
int main()
{
Person a("Zacky",178,'m');
Person b("Jimmy",199,'m');
Person c("Matt",200,'m');
Person d=fmax(a,b,c);
cout<<d<<endl;
cout<<fmax(a,b,c);<<endl;//the error strikes here.
return 0;
}
Apparently I can cout the object d after i've initialised it using the fmax function but can't directly cout what is returned by the function. Any idea about what I need to fix?
P.S. I'm totally sorry if this was asked before, I searched the site and didn't find something similar :/
You need to change the following things:
Since fmax() returns an unchangable rvalue you should use
ostream &operator<<(ostream &mystream, const Person &p);
// ^^^^^
as signature for the output operator overloading (I would recommend doing that in general).
That in turn would require to make your getter functions const member functions:
class Person
{
// ...
const char* getName() const {return this->name;}
int getHeight() const {return this->height;}
char getGender() const {return this->gender;}
};
I've tried looking for a solution but the answers in those questions are very specific. Here's what I have.
The header Code.
class InventoryItem {
public:
InventoryItem(char *desc = 0, double c = 0, int u = 0);
~InventoryItem();
char *getDescription() const;
double getCost() const;
int getUnits() const;
void operator= (const InventoryItem &right);
int setUnits;
private:
char *description;
double cost;
int units;
};
The .cpp file associated with the header file.
InventoryItem::InventoryItem(char *desc, double c, int u) {
description = desc;
cost = c;
units = u;
}
InventoryItem::~InventoryItem() {}
void InventoryItem::operator= (const InventoryItem &right) {
units = right.getUnits();
cost = right.getCost();
description = right.getDescription();
}
The CashRegister class.
class CashRegister {
public:
void getItemToPurchase(InventoryItem) const;
private:
InventoryItem item;
}
The error occurs in this code, which is the .cpp file to the CashRegister function.
void CashRegister::getItemToPurchase(InventoryItem item1) const {
item = item1;
}
It says "No viable operator"=" even though item and item1 are both objects of the same class.
I've compared my code to the one in the book but it still doesn't work.
The problem is with const member function in CashRegister. In CashRegister::getItemOnPurchase(), item is a const member. Hence
item = item1;
is not a viable function.
I can think of couple of ways to solve the problem.
Return the object
InventoryItem CashRegister::getItemToPurchase() const {
return item;
}
Return the object as an output argument.
void CashRegister::getItemToPurchase(InventoryItem& item1) const {
item1 = item;
}
Also, it is more idiomatic to return a reference to the object in the operator= function.
InventoryItem& operator= (const InventoryItem &right);