Overloading operator <<. Error: Invalid operands to binary expression - c++

I am trying to overload a << operator, but I am having weird problem. More precisely there is error:
Invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'Team')
where Team is my class name.
However my friend checked my code and he said that it's working for him. I am coding using Xcode on Mac.
I suppose that it's something with the compiler, isn't it?
That's my code divided into main, .hpp file and .cpp file:
#include <stdio.h>
#include <iostream>
#include "team.hpp"
int main()
{
Team Legia = {"Legia Warszawa", "Warszawa", 283.5, 2, 42};
Team Jagiellonia = {"Jagiellonia Bialystok", "Bialystok", 34.4, 1, 45};
Legia.print();
Jagiellonia.print();
cout << Legia;
cout << Jagiellonia;
return 0;
}
.hpp file
#include <stdio.h>
#include <iostream>
using namespace std;
class Team {
private:
char *name;
char *location;
double budget;
int place;
int points;
public:
Team();
Team(const char*, const char*, double, int, int);
friend ostream& operator<<(ostream& out, const Team &team);
};
.cpp file
#include "team.hpp"
#include <iostream>
#include <string.h>
using namespace std;
Team::Team(const char *_name, const char *_location, double _budget, int _place, int _points)
{
name = new char[strlen(_name)+1];
strcpy(name, _name);
location = new char[strlen(_location)+1];
strcpy(location, _location);
budget = _budget;
place = _place;
points = _points;
}
Team::Team()
{
name = new char[4];
location = new char[8];
strcpy(name, "name");
strcpy(location, "location");
budget = 0;
place = 0;
points = 0;
}
ostream& operator<<(ostream& out, const Team &team)
{
out << "Informations about " << team.name << ": " << endl
<< "Location: " << team.location << endl
<< "Budget: " << team.budget << " millions (PLN)" << endl
<< "Place: " << team.place << endl
<< "Points: " << team.points << endl << endl;
return out;
}
The whole code without formatting:
http://coliru.stacked-crooked.com/a/7f0681a380324222

Related

how can i use aggregation while separating my classes into a .h and .cpp files?

Context
My professor gave me a task to make a program using aggregation between 2 classes while also separating the classes into a .h and .cpp files.
My solution
The header file containing the class declaration:
#include <iostream>
#include <string>
using namespace std;
class medicalCompany {
private:
string ceoName;
string email;
string phoneNumber;
string locate;
public:
medicalCompany();
void Name(string n);
void mail(string m);
void phone(string p);
void location(string l);
~medicalCompany();
};
class origin {
private:
medicalCompany country;
public:
origin();
void address();
~origin();
};
and my .cpp file:
#include <iostream>
#include "function.h"
#include <string>
using namespace std;
medicalCompany::medicalCompany() {
cout << "OUR COMPANY IS GLAD TO BE OF SERVICE !" << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::Name(string n){
ceoName = n;
cout << "OUR CEO IS " << endl;
cout<< ceoName << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::mail(string m) {
email = m;
cout << "USE OUR EMAIL TO CONTACT US : " << endl;
cout<< email << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::phone(string p) {
phoneNumber = p;
cout << "THIS IS OUR CUSTOMER SERVICE PHONE NUMBER " << endl;
cout<< phoneNumber << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::location(string l) {
locate = l;
cout << " OUR COMPANY IS LOCATED IN " << endl;
cout << locate << endl;
cout << "****************************************************" << endl;
}
medicalCompany::~medicalCompany() {
cout << "thanks for trusting our company ^_^" << endl;
cout << "****************************************************" << endl;
}
origin::origin() {
cout<< "constructor 2"<<endl;
}
void origin::address() {
cout << country.location;
}
origin::~origin() {
cout << "bye" << endl;
}
The two classes are used in my main.cpp file:
#include <iostream>
#include <string>
#include "function.h"
using namespace std;
int main() {
medicalCompany o;
o.Name("jack");
o.mail("ouremail#company.com");
o.phone("2342352134");
o.location("Germany");
origin o2;
return 0;
}
Problem
I run into this error :
Severity Code Description Project File Line Suppression State
Error C3867 'medicalCompany::location': non-standard syntax; use '&' to create a pointer to member CP2_HW c:\function.cpp 41
You can either:
replace void origin::address(){cout << country.location;} by void origin::address(){country.location();}
or by void origin::address(){cout << country.locate;} if you put the locate member as a public variable.
Also, few remarks:
Generally you would prefer avoiding exposing private members, so the first solution should be prefered.
the instruction using namespace std; is usually considered bad practice, and should be avoided, as the cost of possible risks does not overweight the benefit of not having to type std::cout(see this question for more information)
In terms of naming convention, I would have exchanged the names of locate and location: location should be the member variable and locate the action (function) of getting the location.
Prefer using a constructor and intialization lists rather than getter/setter.
Your output formatting should be very separate from the logic of your classes, for example implementing a << operator for your class.
Following this logic, your code should look more like:
#include <iostream>
#include <string>
class medicalCompany {
private:
std::string _ceoName;
std::string _email;
std::string _phoneNumber;
std::string _location;
public:
// Constructor
medicalCompany(std::string name, std::string email, std::string phone, std::string location):
_ceoName(name),
_email(email),
_phoneNumber(phone),
_location(location)
{}
friend ostream& operator<<(ostream& os, const medicalCompany& dt);
};
and for the ostream operator:
ostream& operator<<(ostream& os, const medicalCompany& co)
{
os << co._ceoName << " " co._phoneNumber << ' ' << co._email;
return os;
}
This would allows to write code like this in your main:
int main() {
medicalCompany o("jack", "ouremail#company.com","2342352134","Germany")
std::cout << o << std::endl;
return 0;
}
The code is not functional and you would have to edit it to fit your formating requirement, but you have the idea :) Good luck!

C++ Text-Based RPG Inventory System

I'm currently taking a programming 2 class (c++), we've been tasked to make a text based rpg. I'm using this post as a reference for my inventory system, as I think it's pretty effective. But I keep running into a E0349 "no operator "==" or "<<" matches these opperands" error.
If anyone could help me that would be great. Here is my full set of code:
#include "pch.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <ostream>
#include <Windows.h>
#include <string>
#include <cctype>
using namespace std;
struct Item {
string name; //Item name.
int slot; //Head, Torso, Hands
int attack;
int knowledge;
int defense;
int hp;
int speed;
int charisma;
};
int main()
{
//Variables, Strings, etc.
int itemcounter = 0, counter = 0;
//"Empty" Item
Item Empty{ "<Empty>", 0, 0, 0 };
vector<Item> Equipment = { 6, Empty }; //Current Equipment, 6 empty slots.
vector<Item> Inventory = { }; //Player Inventory.
string InventorySlots[] = { "Head" "Torso", "Hands" }; //Player parts where items can be equiped.
cout << "You sit your bag down and take a look inside." << " You have:" << endl;
for (int i = 0; i < itemcounter; i++)
{
cout << InventorySlots[i];
if (Equipment[i] == "Empty ")
{
cout << " " << Equipment[i] << endl << endl;
}
}
}
Here is where my errors are more specifically
for (int i = 0; i < itemcounter; i++) //Display equipped
{
cout << InventorySlots[i];
if (Equipment[i] == "Empty ") //Error Here
{
cout << " " << Equipment[i] << endl << endl; //Errore Here
}
}
Error Message
Error (active) E0349 no operator "<<" matches these operands C:\Users\USER\source\repos\clunkinv\clunkinv\clunkinv.cpp 47
Equipment[i] is an object of type Item. If you don't provide a method to compare your object with "Empty" the compiler can't know how to compare in line
if (Equipment[i] == "Empty ")
Either you compare the property
if (Equipment[i].name == "Empty ")
or you have to provide a method. Same problem in line
cout << " " << Equipment[i] << endl << endl;
The compiler can't know how to print your object. You have to provide a function for this.
You could
struct Item {
string name; //Item name.
int slot; //Head, Torso, Hands
int attack;
int knowledge;
int defense;
int hp;
int speed;
int charisma;
};
std::ostream &operator<<(std::ostream &os, const Item& item) {
os << item.name;
return os;
}
You have to overload operators for your classes if you want to use them.

Default-Constructor when splitting file

got a quick question. Why does the first programm work, but not the one when i split it into header/source file? How can i fix this? (error is that there is no default-constructor for "Stud s [line 6 main.cpp]")
Here is my code:
The working one:
#include <iostream>
#include <string>
using namespace std;
class Stud {
private:
string pren, surn;
unsigned int number;
public:
Stud(string p = "", string s = "", unsigned int n = 0) : pren(p), surn(s), number(n)
{
return;
}
friend ostream& operator<<(ostream& os, Stud& st) {
os << st.number << ", " << st.pren << " " << st.surn;
return os;
}
};
int main() {
Stud s;
Stud test("x", "y", 123);
cout << s << endl;
cout << test << endl;
}
Now the splitted one:
stud.hpp:
#ifndef STUD_HPP
#define STUD_HPP
#include <iostream>
#include <string>
class Stud {
private:
std::string pren, surn;
unsigned int number;
public:
Stud(std::string, std::string, unsigned int);
friend std::ostream& operator<<(std::ostream&, const Stud&);
};
#endif
stud.cpp:
#include "stud.hpp"
Stud::Stud(std::string p = "", std::string s = "", unsigned int n = 0) : pren(p), surn(s), number(n)
{
return;
}
std::ostream& operator<<(std::ostream& os, const Stud& st) {
os << st.number << ", " << st.pren << " " << st.surn;
return os;
}
main.cpp
#include <iostream>
#include "stud.hpp"
using namespace std;
int main() {
Stud s;
Stud test("x", "y", 123);
cout << s << endl;
cout << test << endl;
}

How do I use "<<" with my own struct?

I have following program to access sqlite database and to get the content of a table into a LIST CONTAINER.
All I want is to print the data which is in the list container.But I get this ERROR.
error: expected primary-expression before ‘<<’ token
The below file is DBAccess1.cpp
#include <iostream>
#include <sqlite3.h>
#include <list>
#include <iterator>
#include <algorithm>
#include <string>
#include <cstring>
#include <sstream>
#include "DBAccess1.h"
bool sqliteDB::GET_ALL_Site_Code(list<SiteCode>& Site_Code_list)
{
sqlite3 *db;
const char *sql;
sqlite3_stmt * stmt;
int rc = sqlite3_open("/DBsqlite3/empdbv3.db", &db);
sql = "SELECT * FROM SiteCode;";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
while(sqlite3_step(stmt)==SQLITE_ROW) {
int column = sqlite3_column_count(stmt);
for(int i = 0; i < column; i++)
{
int A = sqlite3_column_int(stmt, 0);
int B = sqlite3_column_int(stmt, 1);
SiteCode info;
info.siteID = A;
info.siteCode = B;
cout<<"Preparing to push data into List"<<endl;
Site_Code_list.push_back(info);
cout<<"Data was pushed successfully"<<endl;
}//FOR LOOP ENDS HERE
}// WHILE LOOP ENDS HERE
sqlite3_finalize(stmt);
sqlite3_close(db);
return true;
}
//=================================XX=============================//
void sqliteDB::printList()
{
int s = Site_Code_list.size();
cout << "The size of List is :" << s << endl;
for( list<SiteCode> :: iterator it = Site_Code_list.begin(); it != Site_Code_list.end(); it++)
cout << it* << " "; //The ERROR occurs here
}
Below is my DBAccess.h file:
#ifndef DBAccess1_HH
#define DBAccess1_HH
#include <iostream>
#include <sqlite3.h>
#include <list>
#include <iterator>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <string>
using namespace std;
struct SiteCode
{
int siteID;
int siteCode;
};
class sqliteDB {
public:
list<SiteCode> Site_Code_list;
bool GET_ALL_Site_Code(list<SiteCode>& Site_Code_list);
void printList();
};
#endif
And below is my main.cpp from where I am calling the functions:
int main()
{
sqliteDB object1;
list<SiteCode> Site_Code_list;
object1.GET_ALL_Site_Code(Site_Code_list);
object1.printList();
cout << "\n\nAll the statement were executed properly\n\n";
return 0;
}
The Error I get is:
error: expected primary-expression before ‘<<’ token
cout << it* << " ";
You have two "errors" in your code. The first is the one that everyone else has pointed out. This
cout << it * << " ";
should be this
cout << *it << " ";
Which if course generates the second error
no match for ‘operator<<’ (operand types are ‘std::ostream
{aka std::basic_ostream<char>}’ and ‘SiteCode’)
std::cout << *it << " ";
Which is actually telling you exactly what the problem is. You are trying to output a SiteCode object onto the stream, but there is no << operator defined for a SiteCode object.
You need to add the following for your SiteCode struct.
ostream& operator<< (ostream &out, SiteCode &site)
{
out << "(" << site.siteID << "," << site.siteCode << ")";
return out;
}
Declare this in the header file, after the struct is defined, thus:
struct SiteCode
{
int siteID;
int siteCode;
};
inline ostream& operator<< (ostream &out, SiteCode &site)
{
out << "(" << site.siteID << "," << site.siteCode << ")";
return out;
}
And now you will be able to use << with any SiteCode object on any stream.
How you actually format the output of the object is up to you. I just chose to display it as a tuple.
Introduction
Dereferencing an iterator is done with *it, not it* - the latter would expect another operand; "multiplication of it and primary-expression".
cout << *it << " "; // fixed
Note
The previous "fix" will require you to define a operator<< suitable for std::cout, and an object of type SiteCode.
If you just want to print the list in a simple manner you can do the following:
cout << it->siteID << " " << it->siteCode << "\n";

C++ Operator '<<' error

I have a question regarding a homework assignment.
I have two classes. One is called ticket.cpp, and the other is called TicketOrder.cpp
The main is within the ticket.cpp.
I am using a g++ compiler on Linux.
What I'm doing is trying to is print out a vector of a TicketOrder object called orders, but it gives me the following error:
ticket.cpp:57: error: no match for 'operator<<' in 'std::cout << orders. std::vector<_Tp, _Alloc>::operator[] with _Tp = TicketOrder, _Alloc = std::allocator'
Here is my code:
ticket.cpp
#include <iostream>
#include <vector>
#include <limits>
#include <cctype>
#include "TicketOrder.cpp"
using namespace std;
int main ()
{
int numberoftickets=0;
string input2;
char input3;
int profit=0;
vector <TicketOrder> orders;
int atotalmoney=0;
int btotalmoney=0;
int ctotalmoney=0;
int dtotalmoney=0;
int etotalmoney=0;
do
{
cout << "\nPick a ticket that you would like to buy: \n\n";
cout << "(A) Students without an activity card: $2.00 \n";
cout << "(B) Faculty and staff: $3.00 \n";
cout << "(C) USC alumni: $5.00 \n";
cout << "(D) UCLA students and alumni: $20.00 \n";
cout << "(E) Everyone else: $10.00 \n";
cin >> input3;
if (input3=='A')
{
cout << "How many tickets do you wish to buy? " <<endl;
if (numberoftickets >0)
{
TicketOrder order;
order.setQuantity(numberoftickets);
order.setType(input3);
orders.push_back(order);
for (int i=0; i< orders.size(); i++)
{
cout << orders[i];
}
}
}
else
{
cout << "Sorry did not recognize input, try again. " << endl;
}
} while (input3 != 'S');
TicketOrder.cpp:
#include <iostream>
using namespace std;
class TicketOrder
{
public :
//Getters
int getQuantity() const
{
return quantity;
}
char getType() const
{
return type;
}
//Setters
void setQuantity (int x)
{
quantity=x;
}
void setType(char y)
{
type =y;
}
private:
char type;
char quantity;
};
As the compiler is clumsily trying to explain, the code is missing an operator<< for the TicketOrder class.
class TicketOrder {
public:
friend std::ostream& operator<<(std::ostream& os, TicketOrder const& order) {
os << "Type: " << type << ", quantity: " << quantity;
return os;
}
char type;
int quantity;
};
(Note: you probably want to change quantity to int.)
You must add the operator << function as a friend to be able to print values from your TicketOrder objects with cout. Further reading
You're attempting to use the << operator on cout and a TicketOrder object. That is undefined. You should use the TicketOrder object to generate a string first, then output that via cout. Either that, or you can define the << operator for the TicketOrder class, as described in one of the other two answers.