Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
I'm learning about friend functions and I was wondering how I could create a friend function in this code to print out the age, and irascibility of the Cat object.
#ifndef CAT H
#define CAT H
#include <string>
class Cat
{
private :
std :: string name ;
int age ;
float irascibility ;
public :
void setName(std :: string n) {name = n;}
std :: string getName ( ) {return name ; }
void setAge(int a) {age = a;}
int getAge( ) {return age ;}
void setIrascibility (float i) {irascibility = i;}
float getIrascibility ( ){return irascibility;}
std :: string meow(int rep)
{
std :: string output = " " ;
for (int i { 0 } ; i < rep − 1 ; i++)
output += "MEOW" ;
if ( rep != 0 )
output += "MEOW" ;
return output ;
}
};
#end if
Since the Cat class already has getters for all its data, just declare those as const and create a regular operator overload.
std::ostream& operator<<(std::ostream& os, const Cat& cat) {
return os << "Cat [name=" << cat.getName() << ", age=" << cat.getAge() << ']';
}
You could do it like this:
#ifndef CAT_H
#define CAT_H
#include <string>
#include <iostream>
class Cat
{
public:
void setName(std::string n)
{
name = n;
}
std::string getName()
{
return name;
}
void setAge(int a)
{
age = a;
}
int getAge()
{
return age;
}
void setIrascibility(float i)
{
irascibility = i;
}
float getIrascibility()
{
return irascibility;
}
std::string meow(int rep)
{
std::string output = " ";
for (int i{0}; i < rep - 1; i++)
output += "MEOW";
if (rep != 0)
output += "MEOW";
return output;
}
friend void printAge(const Cat &cat);
friend void printIrascibility(const Cat &cat);
private:
std::string name;
int age;
float irascibility;
};
void printAge(const Cat &cat)
{
std::cout << cat.age << std::endl;
}
void printIrascibility(const Cat &cat)
{
std::cout << cat.irascibility << std::endl;
}
#endif
But, friend functions are not needed here. although the class properties are private, it has public getters for these properties. Honestly I would do this class like this:
#include <string>
#include <iostream>
struct Cat
{
std::string meow(size_t rep)
{
std::string output{};
for (size_t i{0}; i < rep; i++)
output += "MEOW";
return output;
}
std::string name;
int age;
float irascibility;
};
inline void printAge(const Cat &cat) noexcept
{
std::cout << cat.age << std::endl;
}
inline void printIrascibility(const Cat &cat) noexcept
{
std::cout << cat.irascibility << std::endl;
}
I recommend you to read more c++ code, practice and more practice. Sorry for any mistake.
Related
If anyone can help I would be very grateful.
How do i sort this vector:
vector<Person*>person
by this criterium:
Surname
I have already tried it using set but it removes object if there is more than 2 objects with same Surname
there are lot of string variables, and I need to sort it by
Surname
and then if surnames are the same, then I need to sort them by
Name
and also it sorts by hexadecimal value of that pointer...
EDIT:
More code as you ask:
for (pChild = pRoot->FirstChildElement("Member"); pChild != NULL; pChild = pChild->NextSiblingElement())
{
string Surname = pChild->Attribute("surname");
string Name = pChild->Attribute("name");
string DateOfBirth = pChild->Attribute("dateofbirth");
person.push_back(new Person(Surname, Name, DateOfBirth));
}
Without you showing more of your code, it is hard to help you, but I would look at the documentation for std::sort() as you can create custom operators to sort your vector.
Here's a complete example
#include <vector>
#include <iostream>
#include <algorithm>
class Person
{
public:
std::string s1, s2, s3;
Person(std::string S1, std::string S2, std::string S3) : s1(S1), s2(S2), s3(S3) {}
};
struct less_than_key
{
inline bool operator() (const Person* const p1, const Person* const p2)
{
if (p1->s1 < p2->s1)
return true;
else if (p1->s1 == p2->s1 && p1->s2 < p2->s2)
return true;
return false;
}
};
int main()
{
std::vector<Person*> persons{ new Person("C", "D", "E"), new Person("C", "C", "D"),
new Person("B", "C", "D"), new Person("B", "C", "E")};
std::sort(persons.begin(), persons.end(), less_than_key());
for (auto person : persons)
{
std::cout << person->s1 << ' ' << person->s2 << std::endl;
}
return 0;
}
I had a bit of fun doing it with std::set. There are a couple of examples of comparators. One function and one "functor."
#include <iostream>
#include <set>
#include <string>
struct Person {
uint64_t id;
std::string name;
std::string family_name;
bool operator<(const Person &other) const {
if (family_name == other.family_name) {
if (name == other.name) {
return id < other.id;
} else {
return name < other.name;
}
} else {
return family_name < other.family_name;
}
}
};
std::ostream &operator<<(std::ostream &os, const Person &x) {
return os << '{' << x.id << ", " << x.name << ", " << x.family_name << '}';
}
bool person_ptr_less(const Person *a, const Person *b) { return *a < *b; }
class PersonPtrComparator {
public:
bool operator()(const Person *a, const Person *b) const { return *a < *b; }
};
int main() {
std::set<Person *, bool (*)(const Person *, const Person *)> people(
person_ptr_less);
people.emplace(new Person{1, "Joe", "Smith"});
people.emplace(new Person{2, "Joe", "Blow"});
people.emplace(new Person{3, "Joa", "Smith"});
people.emplace(new Person{4, "Joe", "Smith"});
std::set<Person *, PersonPtrComparator> people_2(people.begin(),
people.end());
for (const auto &x : people) {
std::cout << *x << '\n';
}
std::cout << "---\n";
for (const auto &x : people_2) {
std::cout << *x << '\n';
}
return 0;
}
You can use a comparator like this:
// Simple class
class Person {
public:
string name;
Person(string name) {
this->name = name;
}
};
// create a comparator like this with two objects as parameters.
bool comparator(Person* a, Person *b) {
return a->name > b->name;
}
int main() {
vector<Person* > v;
v.push_back(new Person("ajay"));
v.push_back(new Person("tanya"));
// pass the comparator created into sort function.
sort(v.begin(), v.end(),comparator);
// printing output to check
for(int i=0;i<v.size();i++) {
cout<<v[i]->name<<endl;
}
}
I keep getting this error that only virtual functions can be marked as override but the functions in question "norm()" and "string to_string()" are virtual. what could be causing this?
In my main function I am also getting the error no matching member function to call push back, did I make a mistake along the way somewhere and I am just not seeing it?
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
class Group
{
public:
virtual string to_string() = 0;
virtual int norm() = 0;
};
class Real
{
// add your code here
protected:
int number;
public:
Real(int num)
{
number = num;
}
int norm() override
{
return number;
}
string to_string() override
{
return number;
}
int getNumber() const
{
return number;
}
void setNumber(int number)
{
Real::number = number;
}
};
class Complex : public Real
{
// add your code here
protected:
int imaginary;
public:
Complex(int realNum, int imag) : Real(realNum)
{}
int norm() override
{
return sqrt(number * number + imaginary * imaginary) + 'i';
}
string to_string() override
{
return ::to_string(number) + '+' + ::to_string(imaginary) + 'i';
}
};
class Trinomial : public Complex
{
// add your code here
protected:
int third;
public:
Trinomial(int p1, int p2, int p3) : Complex(p1, p2) {
third = p3;
}
int norm() override {
return sqrt(number * number + imaginary * imaginary + third * third);
}
string to_string() override {
return ::to_string(number) + "x^2+" + ::to_string(imaginary) + "x+" + ::to_string(third);
}
};
class Vector : public Group
{
// add your code here
protected:
vector<int> v;
public:
Vector(int num1, int num2, int num3)
{
v.push_back(num1);
v.push_back(num2);
v.push_back(num3);
}
int norm() override
{
int squared_sum = 0;
for (int i = 0; i < v.size(); i++) {
squared_sum += v[i] * v[i];
}
return sqrt(squared_sum);
}
string to_string() override
{
string str = "[";
for (int i = 0; i < v.size() - 1; i++) {
str += ::to_string(v[i]) + " ";
}
str += ::to_string(v[v.size() - 1]) + "]";
return str;
}
};
int main()
{
vector<Group*> elements;
elements.push_back(new Real{ 3 });
elements.push_back(new Complex{ 3,4 });
elements.push_back(new Trinomial{ 1,2,3 });
elements.push_back(new Vector{ 1,2,3 });
for (auto e : elements)
{
cout << "|" << e->to_string() << "| = " << e->norm() << endl;
}
for (auto e : elements)
delete e;
return 0;
}
A couple of issues here:
The class Real must have inherited from Group so that you could override the functions. That is the reason for the error message.
Secondly the Real::to_string must return a string at the end. You
might convert the integer using std::to_string.
Last but not least the Group must have a virtual destructor for defined behaviour. Read more here: When to use virtual destructors?
In short, you need
#include <string>
class Group
{
public:
// other code
virtual ~Group() = default;
};
class Real: public Group // --> inherited from base
{
// other codes
public:
std::string to_string() override {
return std::to_string(number);
}
};
As a side, please do not practice with using namespace std;
your class real has no parent. so you cant override to_string()
I have a base Class named Animals and 2 derived class Dog and Cat
class Animal{
protected:
std::string name;
std::string color;
public:
std::string getName() {
return name;
}
std::string getColor() {
return color;
}
...
class Cat : public Animal {
private :
int lives;
public :
int getLives() {
return lives;
}
...
class Dog : public Animal {
private :
std::string gender;
public:
std::string getGender(){
return gender;
}
...
and i have e vec of shared_ptr
std::vector<std::shared_ptr<Animal>> animals
I've added some cats and dogs in the vector and i am trying to print all the characteristics of each animal from vector ,using operator >>(this is a homework,we have to use this ) and i did this
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<std::shared_ptr<T>>& v)
{
for (int i = 0; i < v.size(); ++i) {
os << v[i]->getName();
os << "-";
os << v[i]->getColor();
if (i != v.size() - 1)
os << ", ";
os<<"\n";
}
return os;
}
but in this way i can print only the name and color or the animals(these atributes are in the base class)
My question is :
How can i print all the attributes ,for cats lives and for dogs gender???
Try this:
class Animal {
protected:
std::string name;
std::string color;
public:
virtual void print(std::ostream& os){
os << "Name:" << name <<" Color:"<< color;
}
void setName(string n) { name = n; }
void setColor(string c) { color = c; }
std::string getName() {
return name;
}
std::string getColor() {
return color;
}
};
class Cat : public Animal {
private:
int lives;
public:
void setLives(int n) { lives = n; }
void print(std::ostream& os) {
Animal::print(os);
os <<" Lives:"<<lives;
}
int getLives() {
return lives;
}
};
class Dog : public Animal {
private:
std::string gender;
public:
void setGender(string g) { gender = g; }
void print(std::ostream& os) {
Animal::print(os);
os << " Gender:" << gender;
}
std::string getGender() {
return gender;
}
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<std::shared_ptr<T>>& v)
{
for (int i = 0; i < v.size(); ++i) {
v[i]->print(os);
os << "\n";
}
return os;
}
int main()
{
shared_ptr<Dog> d1 = make_shared<Dog>();
d1->setName("Dog1"); d1->setColor("White"); d1->setGender("Male");
shared_ptr<Cat> c1 = make_shared<Cat>();
c1->setName("Cat1"); c1->setColor("Brown"); c1->setLives(1);
vector<shared_ptr<Animal>> vec;
vec.push_back(d1);
vec.push_back(c1);
cout << vec;
return 0;
}
Error
e/c++/v1/algorithm:642:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/utility:321:9: error:
field type 'Space' is an abstract class
_T2 second;
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/map:624:16: note:
Question
How can I define a std::vector of type Space which is an abstract class and then fill this vector with instances of the derived classes Empty, Snake, Ladder.
Context
I know abstract classes in C++ can not be instantiated. Instead I've read in several posts on this and other sites that you can create a collection of an abstract type if it the type is defined as a star * pointer or any of the <memory> managed pointer data types like std::unqiue_ptr<T>. I've tried to used shared_ptr<Space> in my case, but still unable to define the collection properly. I am compiled my code using g++ -std=c++17 main.cpp && ./a.out.
Code
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <map>
#include <memory>
#include <typeinfo>
#include <queue>
#include <string>
#include <vector>
class Player
{
private:
int m_current_space = 1;
public:
Player() {}
void role_dice() {
m_current_space += floor( (rand()%10 + 1) / 3 );
}
int const get_current_space() {
return m_current_space;
}
void set_current_space(int current_space) {
m_current_space = current_space;
}
};
class Space
{
protected:
int m_id;
std::vector<Space> m_paths;
public:
Space() {} // requied to use [] operator in map
Space(int id) : m_id(id) {}
void add_path(Space& s) {
m_paths.push_back(s);
}
int get_id() {
return m_id;
}
virtual std::string class_type() = 0;
};
class Empty : public Space
{
public:
Empty(int id) : Space(id) {}
std::string class_type() {
return "Empty";
}
};
class Ladder : public Space
{
public:
Ladder(int id) : Space(id) {}
virtual void event(Player& p) {
p.set_current_space(1);
}
std::string class_type() {
return "Ladder";
}
};
class Snake : public Space
{
public:
Snake(int id) : Space(id) {}
virtual void event(Player& p) {
p.set_current_space(4);
}
std::string class_type() {
return "Snake";
}
};
class Board
{
private:
std::map<int, Space> m_board;
public:
void add_space(Space& s) {
m_board[s.get_id()] = s;
}
void draw_board() {
int i = 1;
for(auto const& [space_key, space] : m_board) {
if(i%3 == 0) {
std::cout << "○\n";
}
else if(typeid(space) == typeid(Snake)) {
std::cout << "○-";
}
else {
std::cout << "○ ";
}
++i;
}
}
void update_player_on_board(int position) {
int i = 1;
for(auto const& [space_key, space] : m_board) {
if(i%3 == 0) {
if (space_key == position) {
std::cout << "●\n";
}
else {
std::cout << "○\n";
}
}
else if(typeid(space) == typeid(Snake)) {
std::cout << "○-";
}
else {
if (space_key == position) {
std::cout << "● ";
}
else {
std::cout << "○ ";
}
}
++i;
}
}
const std::map<int, Space> get_board() {
return m_board;
}
friend std::ostream &operator<<(std::ostream& os, const Board& b) {
return os;
}
};
class GameStateManager
{
private:
std::string m_state = "game over";
bool m_playing = false;
public:
std::string const get_state() {
return m_state;
}
void set_state(std::string state) {
m_state = state;
}
};
int main()
{
std::cout << "Welcome to Bowser's 9 board game\n";
std::cout << "Start? y(yes) n(no)\n";
GameStateManager game_manager;
game_manager.set_state("playing");
auto space1 = std::make_shared<Space>(1);
auto space2 = std::make_shared<Space>(2);
auto space3 = std::make_shared<Space>(3);
auto space4 = std::make_shared<Space>(4);
auto space5 = std::make_shared<Space>(5);
auto space6 = std::make_shared<Space>(6);
auto space7 = std::make_shared<Space>(7);
auto space8 = std::make_shared<Space>(8);
auto space9 = std::make_shared<Space>(9);
std::vector<std::shared_ptr<Space>> v {
space1, space2, space3,
space4, space5, space6,
space7, space8, space9
};
Board bowsers_bigbad_laddersnake;
for(int i = 0; i < 10; ++i) {
bowsers_bigbad_laddersnake.add_space(*(v[i]));
}
bowsers_bigbad_laddersnake.draw_board();
Player mario;
int turn = 0;
while(game_manager.get_state() == "playing") {
std::cin.get();
std::cout << "-- Turn " << ++turn << " --" << '\n';
mario.role_dice();
bowsers_bigbad_laddersnake.update_player_on_board(mario.get_current_space());
if (mario.get_current_space() >= 9) {
game_manager.set_state("game over");
}
}
std::cout << "Thanks a so much for to playing!\nPress any key to continue . . .\n";
std::cin.get();
return 0;
}
You seem to have removed a lot of code to get into details here.
Have a Space pointer (smart or raw). Instantiate the specific space that you want, point to it with your pointer of type Space. Example std::shared_ptr<Space> pointerToSpace = std::make_shared<Snake> ("I'm a snake"); Now, without loss of generality, you can print the contents (of concrete type) with just the pointer to the space pointerToSpace->class_type(). Yes, you can have a collection of shared_ptrs in a container.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i am new to c++ and i am currently trying to write a program that uses main to call functions which are seperately written and i tried to write the definitions for the header file declarations and i am getting errors with some functions which i have marked in the code
Store.hpp
#ifndef STORE_HPP
#define STORE_HPP
class Product;
class Customer;
#include<string>
#include "Customer.hpp"
#include "Product.hpp"
class Store
{
private:
std::vector<Product*> inventory;
std::vector<Customer*> members;
public:
void addProduct(Product* p);
void addMember(Customer* c);
Product* getProductFromID(std::string);
Customer* getMemberFromID(std::string);
void productSearch(std::string str);
void addProductToMemberCart(std::string pID, std::string mID);
void checkOutMember(std::string mID);
};
#endif
i am having trouble writing the code for that function help me
store.cpp
#include <iostream>
#include <string.h>
#include "Customer.hpp"
#include "Store.hpp"
#include "Product.hpp"
using namespace std;
string id;
void Store::addProduct(Product* p) //error 1 no matching function
{
Product* p(std::string id, std::string t, std::string d, double p, int qa);
inventory.push_back(p);
}
void Store:: addMember(Customer* c)
{
members.push_back(c->getAccountID());
}
Product* Store::getProductFromID(std::string id)
{
for(int i = 0; i < inventory.size(); i++)
{
Product* p=inventory.at(i);
if(p->getIdCode()= id)
{
return p;
}
}
return NULL;
}
Customer* Store:: getMemberFromID(std::string id)
{
for(int i = 0; i < members.size(); i++)
{
Customer* c = members.at(i);
if(c->getAccountID() == id)
{
return c;
}
}
return NULL;
}
void std::Store productSearch(std::string str)
{
for(int i = 0; i < inventory.size(); i++)
{
if(inventory[i] == str)
{
Product stud(inventory[i],inventory[i+1],inventory[i+2],inventory[i+3],inventory[i+4]);
cout<<getIdCode();
cout<<getTitle();
cout<<getDescription();
cout<<getPrice();
cout<<getQuantityAvailable();
}
}
}
void addProductToMemberCart(std::string pID, std::string mID)
{
cout<<"adding to cart"<<endl;
getMemberFromID(mID)->addProductToCart(pID);
}
void checkOutMember(std::string mID)
{
Customer* c=getAccountID(mID)
mID=getMemberFromID(std::string mID);
if(mID=="NULL")
{
cout<<mID<<"is not found"<<endl;
}
}
customer.hpp
#ifndef CUSTOMER_HPP
#define CUSTOMER_HPP
#include<vector>
#include "Product.hpp"
class Customer
{
private:
std::vector<std::string> cart;
std::string name;
std::string accountID;
bool premiumMember;
public:
Customer(std::string n, std::string a, bool pm);
std::string getAccountID();
//std::vector getCart();
void addProductToCart(std::string);
bool isPremiumMember();
void emptyCart();
};
#endif
product.hpp
#ifndef PRODUCT_HPP
#define PRODUCT_HPP
#include<vector>
class Product
{
private:
std::string idCode;
std::string title;
std::string description;
double price;
int quantityAvailable;
public:
Product(std::string id, std::string t, std::string d, double p, int qa);
std::string getIdCode();
std::string getTitle();
std::string getDescription();
double getPrice();
int getQuantityAvailable();
void decreaseQuantity();
};
#endif
You code issues lots of warnings and errors as stands.
If you find yourself in this situation and can't figure out what one of them means, try to fix some of the others.
Your main problem is in addProduct, but there are others
using namespace std;
string id; //<---- what's this for?
void Store::addProduct(Product* p) //error 1 no matching function
{
//Product* p(std::string id, std::string t, std::string d, double p, int qa);
//<--- This line had the error and isn't needed
inventory.push_back(p);
}
void Store::addMember(Customer* c)
{
// members.push_back(c->getAccountID()); //<--- this errors too
members.push_back(c);
}
Product* Store::getProductFromID(std::string id)
{
for (size_t i = 0; i < inventory.size(); i++)
{
Product* p = inventory.at(i);
//if (p->getIdCode() = id) //<-- be careful with = and ==
if (p->getIdCode() == id) //<---
{
return p;
}
}
return NULL;
}
Customer* Store::getMemberFromID(std::string id)
{
for (size_t i = 0; i < members.size(); i++)
{
Customer* c = members.at(i);
if (c->getAccountID() == id)
{
return c;
}
}
return NULL;
}
//void std::Store productSearch(std::string str)
void Store::productSearch(std::string str) // <---- note this change too
{
for (size_t i = 0; i < inventory.size(); i++)
{
//if (inventory[i] == str) //<<--------!
if (inventory[i]->getDescription() == str)
{
//Product stud(inventory[i], inventory[i + 1], inventory[i + 2], inventory[i + 3], inventory[i + 4]);
// This is five Products from the inventory, not the i-th product in your invetory
Product stud(*inventory[i]);//<---- I assume
cout << stud.getIdCode();
cout << stud.getTitle();
cout << stud.getDescription();
cout << stud.getPrice();
cout << stud.getQuantityAvailable();
}
}
}
void Store::addProductToMemberCart(std::string pID, std::string mID)//<--- note note std::Store addProductToMemberCart
{
cout << "adding to cart" << endl;
getMemberFromID(mID)->addProductToCart(pID);
}
void Store::checkOutMember(std::string mID)//<---
{
//Customer* c = getAccountID(mID);//<<---?
//mID = getMemberFromID(std::string mID); //<---?
Customer* c = getMemberFromID(mID); //Just this?
if (c == NULL)//<---rather than "NULL" but nullptr might be better
{ // or not using pointers at all
cout << mID << "is not found" << endl;
}
}