Retrieving values of an object from an array? - c++

Pardon the example but in this case:
#include <iostream>
#include <string>
using namespace std;
class A {
private:
string theName;
int theAge;
public:
A() : theName(""), theAge(0) { }
A(string name, int age) : theName(name), theAge(age) { }
};
class B {
private:
A theArray[1];
public:
void set(const A value) {theArray[0] = value; }
A get() const { return theArray[0]; }
};
int main()
{
A man("Bob", 25);
B manPlace;
manPlace.set(man);
cout << manPlace.get();
return 0;
}
Is it possible for me to retrieve the contents of the "man" object in main when I call manPlace.get()? My intention is to print both the name (Bob) and the age (25) when I call manPlace.get(). I want to store an object within an array within another class and I can retrieve the contents of said array within the main.

You need to define a ostream::operator<< on your A class to accomplish that - otherwise the format how age and name should be generated as text-output is undefined (and they are private members of your A class).
Take a look at the reference for ostream::operator<<. For your A class, such a operator could be defined like this:
std::ostream& operator<< (std::ostream &out, A &a) {
out << "Name: " << a.theName << std::endl;
out << "Age: " << a.theAge << std::endl;
return out;
}
Which would output something like:
Name: XX
Age: YY
So your complete code would be:
#include <iostream>
#include <string>
using namespace std;
class A {
private:
string theName;
int theAge;
public:
A() : theName(""), theAge(0) { }
A(string name, int age) : theName(name), theAge(age) { }
friend std::ostream& operator<< (std::ostream &out, A &a) {
out << "Name: " << a.theName << std::endl;
out << "Age: " << a.theAge << std::endl;
return out;
}
};
class B {
private:
A theArray[1];
public:
void set(const A value) { theArray[0] = value; }
A get() const { return theArray[0]; }
};
int main()
{
A man("Bob", 25);
B manPlace;
manPlace.set(man);
cout << manPlace.get();
return 0;
}
which will output:
Name: Bob
Age: 25

Related

How can I output all objects in a vector using for loop in c++

A class BookLibrary constructs a vector of objects of class BookInfo. The task is to add some 'books' (objects of class BookInfo) into the vector and print them out. For some reason, a conventional for(unsigned int i = 0; i < vector.size(); i++) cout << vector[i] << endl; loop is not working. This is a homework project from Savitch textbook "Problem Solving with C++".
Here's the code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class BookInfo
{
public:
BookInfo(string newAuthor, string newTitle);
BookInfo(string newTitle);
string getName();
string getAuthor();
string getTitle();
private:
string author;
string title;
};
class BookLibrary
{
public:
BookLibrary();
BookLibrary(vector<BookInfo> newLibrary);
void add(BookInfo newBook);
void size();
void printInfo();
private:
vector<BookInfo> library;
};
int main()
{
BookLibrary library1;
BookInfo book1("Michael Krichton", "Jurassic Park");
BookInfo book2("War and Peace"), book3("Valter Savitch", "Programming in C++");
library1.add(book1);
library1.add(book2);
library1.add(book3);
library1.size();
library1.printInfo();
return 0;
}
BookInfo::BookInfo(string newAuthor, string newTitle)
{
author = newAuthor;
title = newTitle;
}
BookInfo::BookInfo(string newTitle) :
title(newTitle), author("unknown")
{}
string BookInfo::getName()
{
return (author + " " + title);
}
string BookInfo::getAuthor()
{
return author;
}
string BookInfo::getTitle()
{
return title;
}
BookLibrary::BookLibrary()
{}
BookLibrary::BookLibrary(vector<BookInfo> newLibrary)
{
library = newLibrary;
}
void BookLibrary::add(BookInfo newBook)
{
library.push_back(newBook);
}
void BookLibrary::size()
{
cout << library.size();
}
void BookLibrary::printInfo()
{
for (unsigned int i = 0; i < library.size(); i++)
cout << library[i] << endl;
}
It underlines the cout << in the last line.
Your loop is not able to print out a BookInfo object, because you have not defined an operator<< for BookInfo. As such, a statement like cout << library[i] does not know what to do with the BookInfo that library[i] returns.
You need to add that operator, eg:
class BookInfo
{
public:
...
friend ostream& operator<<(ostream &os, const BookInfo &book)
{
os << "\"" << book.title << "\" by " << book.author;
return os;
}
...
};
If you want to use your getName() method instead, you would need to declare it as const (which you should do anyway for all of your getters), eg:
class BookInfo
{
public:
...
string getName() const;
...
friend ostream& operator<<(ostream &os, const BookInfo &book)
{
os << book.getName();
return os;
}
...
};
string BookInfo::getName() const
{
return ...;
}

How to return the member of template derived class from base?

Is it possible to return a template member of a derived class by the base?
Please find the following classes:
Data.h:
#include <string>
class IData{
public:
virtual ~IData(){};
virtual const std::string& getName() const = 0;
};
template <typename T>
class DataImpl: public IData
{
public:
DataImpl(const std::string& name, T* ptrToData)
:_name(name)
,_ptrToData(ptrToData)
{};
~DataImpl(){};
const std::string& getName() const
{
return _name;
}
const T* getDataPtr() const
{
return _ptrToData;
}
private:
std::string _name;
T* _ptrToData; // <-- how to return this pointer ?
};
Component.h:
#include <vector>
#include <string>
#include "Data.h"
class Component
{
public:
Component(const std::string& name)
:_name(name)
{};
~Component(){};
const std::string& getName() const
{
return _name;
};
std::vector<IData*>& getDataList()
{
return _dataList;
};
void addData(IData* ptr)
{
_dataList.push_back(ptr);
};
private:
std::string _name;
std::vector<IData*> _dataList;
};
main.cpp:
#include <iostream>
#include <vector>
#include <string>
#include "Component.h"
#include "Data.h"
int main()
{
// primitive types
int x = 5;
float y = 5.7;
bool b = false;
// complex structures
struct complex{
int a;
std::string c;
};
complex cx;
cx.a = 5;
cx.c = "anything";
DataImpl<int> d1("x", &x);
DataImpl<float> d2("y", &y);
DataImpl<bool> d3("b", &b);
DataImpl<complex> d4("complex", &cx);
Component cmp("cmpName");
cmp.addData(&d1);
cmp.addData(&d2);
cmp.addData(&d3);
cmp.addData(&d4);
std::vector<IData*>::iterator it = cmp.getDataList().begin();
for (;it != cmp.getDataList().end(); ++it)
{
IData* ptr = *it;
std::cout << ptr->getName() << std::endl;
}
return 0;
}
Inside the loop in the main.cpp, I was accessing every DataImpl member. But I want to return/get the member variable T* _ptrToData through the base class IData but so far I did not find any way.
I have a compiler restriction to c++98
Thanks in advance.
You can try to use dynamic_cast to perform a type-safe downcast of the IData* pointer back to the pointer of the derived class (e.g. DataImpl<int>* ) . However, this may require the Run-time type information (RTTI) of the compiler enabled.
Here's an example:
for (;it != cmp.getDataList().end(); ++it)
{
IData* ptr = *it;
std::cout << ptr->getName() << std::endl;
DataImpl<int>* pInt = dynamic_cast<DataImpl<int>*>(ptr);
if (pInt) {
std::cout << "*pInt->getDataPtr(): " << *pInt->getDataPtr() << std::endl;
std::cout << "pInt->getDataPtr(): " << pInt->getDataPtr() << std::endl;
}
DataImpl<float>* pfloat = dynamic_cast<DataImpl<float>*>(ptr);
if (pfloat) {
std::cout << "*pfloat->getDataPtr(): " << *pfloat->getDataPtr() << std::endl;
std::cout << "pfloat->getDataPtr(): " << pfloat->getDataPtr() << std::endl;
}
DataImpl<bool>* pbool = dynamic_cast<DataImpl<bool>*>(ptr);
if (pbool) {
std::cout << "*pbool->getDataPtr(): " << *pbool->getDataPtr() << std::endl;
std::cout << "pbool->getDataPtr(): " << pbool->getDataPtr() << std::endl;
}
}

how to use struct in a class

lifeform.h
class lifeform
{
public:
struct item;
void buyItem(item &a);
//code..
};
lifeform.cpp
struct lifeform::item
{
std::string type,name;
bool own;
int value,feature;
item(std::string _type,std::string _name,int _value,int _feature):type(_type), name(_name),value(_value),feature(_feature)
{
own=false;
}
};
lifeform::item lBoots("boots","Leather Boots",70,20);
void lifeform::buyItem(item &a)
{
if(a.own==0)
{
inventory.push_back(a);
a.own=1;
addGold(-a.value);
std::cout << "Added " << a.name << " to the inventory.";
if(a.type=="boots")
{
hp-=inventory[1].feature;
inventory[1]=a;
std::cout << " ( HP + " << a.feature << " )\n";
maxHp+=a.feature;
hp+=a.feature;
}
}
there is no error so far but when i wanna use them in main.cpp like this
#include "lifeform.h"
int main()
{
lifeform p;
p.buyItem(lBoots);
}
compiler says me [Error] 'lBoots' was not declared in this scope but i declared it class am i missing something?
To use your lifeform::item lBoots you need to declare it in main:
#include "lifeform.h"
extern lifeform::item lBoots; // <-- you need this.
int main()
{
lifeform p;
p.buyItem(lBoots);
}
Or alternatively you should place extern lifeform::item lBoots; in your lifeform.h.

debugging error at the end of the console

I'm a student and I studying c++.
This is my cpp code
int _tmain(int argc, _TCHAR* argv[])
{
CFood output;
output.whatFunc();
cout<<"my outputs"<<endl<<output<<endl;
return 0;
}
ostream& operator <<(ostream& outputStream, const CFood& output)
{
for(int i=0; i<2; i++)
{
outputStream <<"1 : "<<output.m_strName[i]<<" 2 : "<<output.m_servingSize[i]<<"g "<<"3 : "<<
output.m_calorie[i]<<"cal "<<"4 : "<<output.m_transFat[i]<<"g"<<endl;
}
return outputStream;
}
When I debug it, It work. But the end of the console, it gives me error message;;;
It says "An unhandled win32 exception occurred in work.exe [5796]"
My header filed is
class CFood
{
public:
CFood(void);
~CFood(void);
private:
string m_strName[7];
double m_servingSize[7];
double m_calorie[7];
double m_transFat[7];
public:
void whatFunc(void);
friend ostream& operator <<(ostream& outputStream,const CFood& output);
}
I think there is something wrong in my code..And I think it's CFood output;(Just thinking..)
Do you know why it has debug error?
++Sorry, I forgot the whatFunc(void)
This is code
void CFood::whatFunc(void) //
{
m_strName[0]="chicken";
m_strName[1]="rice";
m_strName[2]="meat";
m_strName[3]="strawberry";
m_strName[4]="apple";
m_strName[5]="water";
m_strName[6]="juice";
m_servingSize[0]=10;
m_servingSize[1]=20;
m_servingSize[2]=30;
m_servingSize[3]=40;
m_servingSize[4]=50;
m_servingSize[5]=60;
m_servingSize[6]=70;
m_calorie[0]=10.45;
m_calorie[1]=20.57;
m_calorie[2]=30.78;
m_calorie[3]=40.23;
m_calorie[4]=50.85;
m_calorie[5]=60.73;
m_calorie[6]=70.27;
m_transFat[0]=0.01;
m_transFat[1]=0.02;
m_transFat[2]=0.03;
m_transFat[3]=0.04;
m_transFat[4]=0.05;
m_transFat[5]=0.06;
m_transFat[6]=0.07;
}
Well its difficult to tell what exactly goes wrong without full source code. In my humble opinion, entire source lefts much to be desired. Placing obviously linked data in the bunch of the unlinked arrays with static size is not a very good pattern. Instead try something like that:
#include <iostream>
#include <vector>
#include <string>
#include <ostream>
struct CFoodItem{
std::string m_strName;
double m_servingSize;
double m_calorie;
double m_transFat;
};
class CFood
{
public:
void AddFoodItem(const CFoodItem& cItem);
friend std::ostream& operator <<(std::ostream& outputStream, const CFood& output);
private:
std::vector<CFoodItem> m_vItems;
};
std::ostream& operator <<(std::ostream& outputStream, const CFood& output)
{
for (auto i = output.m_vItems.begin(); i != output.m_vItems.end(); ++i)
{
outputStream << "1 : " << i->m_strName << " 2 : " << i->m_servingSize << "g " << "3 : " <<
i->m_calorie << "cal " << "4 : " << i->m_transFat << "g" << std::endl;
}
return (outputStream);
}
void CFood::AddFoodItem(const CFoodItem& cItem)
{
m_vItems.push_back(cItem);
}
int __cdecl main(void)
{
CFood output;
CFoodItem itm;
itm.m_strName = "some food";
itm.m_servingSize = 100500;
itm.m_calorie = 42;
itm.m_transFat = 42;
output.AddFoodItem(itm);
std::cout << "my outputs" << std::endl << output << std::endl;
return 0;
}

how to print using iterator in c++?

I am writing a program in VC++. Here I am declaring class Product and Client.In client I'm using a function list initProduct() in which list::iterator i; is used.I'm unable to display list using iterator.
This my code:
#include "StdAfx.h"
#include <iostream>
#include <string>
#include <list>
#include <iterator>
using namespace std;
class Product
{
int item_code;
string name;
float price;
int count;
public:
void get_detail()
{
cout<<"Enter the details(code,name,price,count)\n"<<endl;
cin>>item_code>>name>>price>>count;
}
};
class Client
{
public:
list<Product> initProduct()
{
char ans='y';
list<Product>l;
list<Product>::iterator i;
while(ans=='y')
{
Product *p = new Product();
p->get_detail();
l.push_back(*p);
cout<<"wanna continue(y/n)"<<endl;
cin>>ans;
}
cout<<"*******"<<endl;
for(i=l.begin(); i!=l.end(); i++)
cout << *i << ' '; //ERROR no operator << match these operand
return l;
}
};
int main()
{
Client c;
c.initProduct();
system("PAUSE");
}
You must implement the following function
class Product {
// ...
friend std::ostream& operator << (std::ostream& output, const Product& product)
{
// Just an example of what you can output
output << product.item_code << ' ' << product.name << ' ';
output << product.price << ' ' << product.count;
return output;
}
// ...
};
You declare the function a friend of the class because it must be able to access the private properties of a Product.
You need to produce an ostream& operator<<(ostream& os, const Product& product) that prints the information you want to display.
If you're using C++11 you can use auto :
for(auto it : Product)
{
cout << it.toString();
}
but you'll have to implement this toString() which will display all the infos you want