I am replacing a Read in function with a friend operator. I am having trouble referencing the friend operator in a void function. I am receiving and error "No member named 'Read' in Date" in the void GetDates function. Does anyone know how to fix this? Thank you!
Question 2:
I am now using cout<< operator but I am receiving errors for my variables: "'mn' is a private member of 'Date'"
class Date {
private:
int mn; //month component of a date
int dy; //day component of a date
int yr; //year comonent of a date
public:
//constructors
Date() : mn(0), dy(0), yr(0)
{}
Date(int m, int d, int y) : mn(m), dy(d), yr(y)
{}
//input/output functions
friend istream& operator>>(istream& Read, Date& d); //overload friend Read
friend ostream& operator<<(istream& write, Date& d); //overload friend write
void GetDates();
void Sort();
};
//Date class member functions
istream& operator >>(istream& Read, Date& d) //**NEED TO REPLACE with overload vs as friends to Date function**
{
char skip_char;
Read >> d.mn >> skip_char >> d.dy >> skip_char >> d.yr;
return Read;
}
void GetDates(Date l[], int &n) //reads list l, and returns count in n
{
cout << "How many date values are to be processed (1 - 100)? ";
cin >> n;
while ((n < 0) || (n > 100)) {
cout << "Invalid value; enter number between 0 and 100: ";
cin >> n;
}
for (int i = 0; i < n; i++) {
cout << "Enter a date (mm/dd/yyyy): ";
l[i].Read(); //ERROR HERE
}
}
ostream& operator <<(ostream& write, Date& d) //friend write
{
if (d.mn < 10)
cout << '0';
cout << d.mn << '/';
if (d.dy < 10)
cout << '0';
cout << d.dy << '/';
if (d.yr < 1000)
cout << '0';
if (d.yr < 100)
cout << '0';
if (d.yr < 10)
cout << '0';
cout << d.yr;
return write;
}
Read is the name of the stream that you are extracting from. An example of a stream that you can read from is cin. You need to replace this line:
l[i].Read(); //ERROR HERE
with
cin >> l[i];
Inside operator>> the cin object is now called Read.
The issue with your operator<< is that it needs to be declared as a friend, the same way you've done with operator>>.
Also, you are writing to cout instead of writing to write. This will not work, as soon as you try to writing to any other stream.
Related
Hello I have an assignment to implement a Matrix class using pointers.
class matrixType{
private:
int **matrix;
int numRows;
int numColumns;
public:
istream& operator >>(istream& ins, const matrixType& source);
}
I'm having trouble with the input operator for this! For some reason this operator overload is not making sense to me, but I also have a function that also allows for user input which isn't an overload.
void matrixType::setMatrix(){
int i,k,value;
cout << "Be prepared to enter values to be inserted into your matrix: " << endl;
for(i=0; i<rowSize; i++){
for(k=0; k<columnSize; ++k){
cout << "Value [" << i << "][" << k << "]: ";
cin >> value;
matrix[i][k]=value;
}
}
cout << endl;
}
Can someone help me on the input operator?
Thank you!
The input operator overloading function allows you to use the object of a class or struct directly into function like cin. This way you can directly ask for all inputs by writing a single statement that inputs the object and it will input all the values itself.
The program should be like
class matrixType{
private:
int **matrix;
int numRows;
int numColumns;
public:
istream& operator>>(istream& input, const matrixType& source)
{
for(int i=0;i<numRows;i++)
for(int j=0;j<numColumns;j++)
input>>source.matrix[i][j];
return input;
}
}
Now You can input the values directly using cin like this
matrixType A;
cin>>A;
I have some code below that will take some names and ages and do some stuff with them. Eventually it will print them out. I need to change my print() function with a global operator<<. I saw on a different forum that <<operator takes two parameters, but when I try it I get a "too many parameters for << operation error. Is there something I am doing wrong? I am newer to C++ and I really do not get the point of operator overloading.
#include <iostream>;
#include <string>;
#include <vector>;
#include <string.h>;
#include <fstream>;
#include <algorithm>;
using namespace::std;
class Name_Pairs{
vector<string> names;
vector<double> ages;
public:
void read_Names(/*string file*/){
ifstream stream;
string name;
//Open new file
stream.open("names.txt");
//Read file
while(getline(stream, name)){
//Push
names.push_back(name);
}
//Close
stream.close();
}
void read_Ages(){
double age;
//Prompt user for each age
for(int x = 0; x < names.size(); x++)
{
cout << "How old is " + names[x] + "? ";
cin >> age;
cout<<endl;
//Push
ages.push_back(age);
}
}
bool sortNames(){
int size = names.size();
string tName;
//Somethine went wrong
if(size < 1) return false;
//Temp
vector<string> temp = names;
vector<double> tempA = ages;
//Sort Names
sort(names.begin(), names.end());
//High on performance, but ok for small amounts of data
for (int x = 0; x < size; x++){
tName = names[x];
for (int y = 0; y < size; y++){
//If the names are the same, then swap
if (temp[y] == names[x]){
ages[x] = tempA[y];
}
}
}
}
void print(){
for(int x = 0; x < names.size(); x++){
cout << names[x] << " " << ages[x] << endl;
}
}
ostream& operator<<(ostream& out, int x){
return out << names[x] << " " << ages[x] <<endl;
}
};
You are overloading << operator as a member function, therefore, the first parameter is implicitly the calling object.
You should either overload it as friend function or as a free function. For example:
overloading as friend function.
friend ostream& operator<<(ostream& out, int x){
out << names[x] << " " << ages[x] <<endl;
return out;
}
However, the canonical way is to overload it as free function. You can find very good information from this post: C++ operator overloading
declare operator overloading function as friend.
friend ostream& operator<<(ostream& out, int x)
{
out << names[x] << " " << ages[x] <<endl;
return out;
}
I posted earlier for the first time and was able to almost complete this assignment. The program isn't giving an error, but I'm getting undesired results. The output appears to be outputting the array address instead of the data I input. Or at least I think it is based on my very very limited knowledge. Can anyone help guide me in how to fix this? I've been working on this all day and at this hour, I think I'm ready to throw in the towel. Any advice is greatly appreciated, thanks!
// Amanda
// SoccerPlayer.cpp : main project file.
// October 6, 2012
/* a. Design a SoccerPlayer class that includes three integer fields: a player's jersey number,
number of goals, and number of assists. Overload extraction and insertion operators for the class.
b. Include an operation>() function for the class. One SoccerPlayer is considered greater
than another if the sum of goals plus assists is greater.
c. Create an array of 11 SoccerPlayers, then use the > operator to find the player who has the
greatest goals plus assists.*/
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
class SoccerPlayer
{
friend std::ostream& operator<<(std::ostream&, const SoccerPlayer&);
friend istream& operator>>(istream&, SoccerPlayer&);
private:
int jerseyNum;
int numGoals;
int numAssists;
public:
SoccerPlayer(int, int, int);
int score;
int operator>(SoccerPlayer&);
void DisplayStar();
};
SoccerPlayer::SoccerPlayer(int jersey = 0, int goal = 0, int assist = 0)
{
jerseyNum = jersey;
numGoals = goal;
numAssists = assist;
}
void SoccerPlayer::DisplayStar()
{
cout<<"Player Number: "<< jerseyNum <<endl;
cout<<"Goals Scored: "<< numGoals <<endl;
cout<<"Assists Made: "<< numAssists <<endl;
}
std::ostream& operator<<(std::ostream& player, const SoccerPlayer& aPlayer)
{
player << "Jersey #" << aPlayer.jerseyNum <<
" Number of Goals " << aPlayer.numGoals <<
" Number of Assists " << aPlayer.numAssists;
return player;
}
std::istream& operator>>(std::istream& inPlayer, SoccerPlayer& aPlayer)
{
cout << "Please enter the jersey number: ";
inPlayer >> aPlayer.jerseyNum;
cout << "Please enter the number of goals: ";
inPlayer >> aPlayer.numGoals;
cout << "Please enter the number of assists: ";
inPlayer >> aPlayer.numAssists;
aPlayer.score=(aPlayer.numGoals) + (aPlayer.numAssists);
return inPlayer;
}
int SoccerPlayer::operator>(SoccerPlayer& aPlayer)
{
int total = 0;
if (score > aPlayer.score)
total = 1;
return total;
}
int main()
{
const int sz = 11;
int x;
SoccerPlayer aPlayer[sz];
for(x = 0; x < sz; ++x)
cin >> aPlayer[x];
{
double max = aPlayer[x].score;
for(int i = 1; i<sz; ++i)
{
if(aPlayer[i] > aPlayer[x])
{
max=aPlayer[i].score;
}
}
cout << max << endl;
cout << aPlayer[x];
}
_getch();
return 0;
}
It looks as if you intended a loop here, but it's malformed:
for(x = 0; x < sz; ++x)
cin >> aPlayer[x];
{
double max = aPlayer[x].score;
for(int i = 1; i<sz; ++i)
{
if(aPlayer[i] > aPlayer[x])
{
max=aPlayer[i].score;
}
}
cout << max << endl;
cout << aPlayer[x];
}
You meant (I think) that double max ... should be inside the loop, but the cin >> ... line comes after the for statement, outside the braces. So the iteration applies only to the cin >> ... statement; once it's done, control proceeds to double max = aPlayer[x].score;, but x (left over from for(...)) is equal to sz, so aPlayer[x] is outside the array, in no-man's-land.
Put the cin >> ... inside the brackets.
The problem is that you only print the element aPlayer[x]. But notice that your first for loop terminates when x = 11. Well, that's one past the end of the array, so really, you're outputting junk.
I just tried it out with aPlayer[0] instead and got expected results.
This is what I ended up with. Thanks everyone for the help!
// Amanda
// SoccerPlayer.cpp : main project file.
// October 6, 2012
/* a. Design a SoccerPlayer class that includes three integer fields: a player's jersey number,
number of goals, and number of assists. Overload extraction and insertion operators for the class.
b. Include an operation>() function for the class. One SoccerPlayer is considered greater
than another if the sum of goals plus assists is greater.
c. Create an array of 11 SoccerPlayers, then use the > operator to find the player who has the
greatest goals plus assists.*/
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
//soccer player class - see above description
class SoccerPlayer
{
friend std::ostream& operator<<(std::ostream&, const SoccerPlayer&);
friend istream& operator>>(istream&, SoccerPlayer&);
private:
int jerseyNum;
int numGoals;
int numAssists;
public:
SoccerPlayer(int, int, int);
int score;
int operator>(SoccerPlayer&);
void DisplayStar();
};
//soccerplayer constructor
SoccerPlayer::SoccerPlayer(int jersey = 0, int goal = 0, int assist = 0)
{
jerseyNum = jersey;
numGoals = goal;
numAssists = assist;
}
//to display star player
void SoccerPlayer::DisplayStar()
{
cout<<"Jersey #: "<< jerseyNum <<endl;
cout<<"Goals Scored: "<< numGoals <<endl;
cout<<"Assists Made: "<< numAssists <<endl;
}
//overload operator out
std::ostream& operator<<(std::ostream& player, const SoccerPlayer& aPlayer)
{
player << "Jersey #" << aPlayer.jerseyNum <<
" Number of Goals " << aPlayer.numGoals <<
" Number of Assists " << aPlayer.numAssists;
return player;
}
//overload operator in
std::istream& operator>>(std::istream& inPlayer, SoccerPlayer& aPlayer)
{
cout << "Please enter the jersey number: ";
inPlayer >> aPlayer.jerseyNum;
cout << "Please enter the number of goals: ";
inPlayer >> aPlayer.numGoals;
cout << "Please enter the number of assists: ";
inPlayer >> aPlayer.numAssists;
aPlayer.score=(aPlayer.numGoals) + (aPlayer.numAssists);
return inPlayer;
}
//overload operator greater than
int SoccerPlayer::operator>(SoccerPlayer& aPlayer)
{
int total = 0;
if (score > aPlayer.score)
total = 1;
return total;
}
//main declaration
int main()
{
//11 players
const int sz = 11;
int x;
SoccerPlayer aPlayer[sz];
double max = 0;
//to display star
SoccerPlayer Star;
//allow user to input players, show what they input
for(x = 0; x < sz; ++x)
{
cin >> aPlayer[x];
cout << aPlayer[x] << endl << endl;
for(int i=1; i<sz; i++)
{
Star=aPlayer[0];
if(aPlayer[i] > aPlayer[i+1])
Star=aPlayer[i];
}
}
//show star player
cout << "The Star Player: "<< endl;
Star.DisplayStar();
_getch();
return 0;
}
There is more code to this question in this previous question: C++ Trouble Inputting Data into Private Vector (invalid use)
I'm trying to output a vector of type "Account"
Account:
class Account
{
string firstName;
string lastName;
string accountPass;
int accountID;
float accountBalance;
private:
int depositAmount;
int withdrawAmount;
public:
static Account createAccount( int, float, string, string, string ); //creates new account
void deposit( int ); //deposits money into account
void withdraw(int); //withdrawals money from account
int retdeposit() const; //function to return balance amount
friend class BankingSystem;
}; //end of class Account
This is the way I'm declaring the vector:
std::vector<Account> accounts_;
And here's how I'm trying to print it to the screen:
for(int i=0; i < accounts_.size(); i++)
{ cout<< accounts_[i] <<endl; }
But I'm getting this error "invalid operands to binary expression".
Current code;
class BankingSystem
{
int accountID;
char fileName;
private:
std::vector<Account> accounts_;
public:
void addAccount();
void storeAccount( Account );
void deleteAccount();
void accountInquiry();
void saveAccounts();
void loadAccountsFromFile();
friend class Account;
friend std::ostream& operator << (std::ostream&, const Account&);
}; // end of class BankingSystem
#endif
std::ostream& operator << (std::ostream& os, const Account& acc)
{
// output members to os
return os;
}
void BankingSystem::addAccount()
{
int ID;
float balance;
std::string pass, first, last;
cout << "\n\t Enter the Account ID: ";
cin >> ID;
cout << "\n\t Enter the passcode: ";
cin >> pass;
cout << "\n\t Enter Client's first name: ";
cin >> first;
cout << "\n\t Enter Client's last name: ";
cin >> last;
cout << "\n\t Enter starting balance: ";
cin >> setw(6) >> balance;
storeAccount( Account::createAccount( ID, balance, pass, first, last ) );
return;
}
//function gets data from createAccount
void BankingSystem::storeAccount( Account newAccountToAdd )
{
//append to vector "accounts_"
accounts_.push_back(newAccountToAdd);
}
void BankingSystem::deleteAccount()
{
cout << "\nEnter The Account ID: ";
cin >> accountID;
}
void BankingSystem::accountInquiry()
{
int n;
cout << "\n\t Enter The Account ID (-1 for all): ";
cin >> n;
//cout << accounts_.size();
if (n == -1)
{
cout << "\n\t List of all Accounts; (" << accounts_.size() << ") TOTAL: ";
for(int i=0; i < accounts_.size(); i++)
{
cout<< accounts_[i] << endl;
}
}
else
{
cout << "\n\t Listing Account: " << n;
cout << "\n\t I should search the vector for the ID you input";
}
}
You need to provide the insertion operator:
std::ostream& operator<<( std::ostream& out, const Account& acct );
Then implement it internally by dumping each one of the fields with the appropriate format.
You should overload operator << for Account class. In class:
friend std::ostream& operator << (std::ostream&, const Account&);
In global (or yours, where Account is defined) namespace
std::ostream& operator << (std::ostream& os, const Account& acc)
{
// output members to os
return os;
}
or create some output function in class for example
void print(std::ostream& os) const { }
And then free-operator <<
std::ostream& operator << (std::ostream& os, const Account& acc)
{
acc.print(os);
return os;
}
I am having serious trouble with my program in C++. I need to read in a line of information entered by the user such as:
Bill Jones 20 07:30 09:30 08:00 14:00 00:00 00:00 10:00 13:00 00:00 00:00
This should all be stored in one instance of a Worker class. What I am having trouble with are the times since they use a semicolon. I am completely stuck and have looked everywhere but can't find any help. This is the code I have so far:
#include <iostream>
#include <string>
using namespace std;
class Time;
class Worker;
ostream &operator << (ostream &, const Time &);
istream &operator >> (istream &, Time &);
class Time
{
private:
int hour;
int minute;
public:
Time();
void setHour(int a)
{ hour=a; }
void setMinute(int a)
{ minute=a; }
int getHour() const
{ return hour; }
int getMinute() const
{ return minute; }
Time operator + (const Time &);
};
class Worker
{
public:
int start;
int end;
string fName;
string lName;
double payrate;
double payment;
Time monday,tuesday,wednesday,thursday,friday;
friend istream &operator >> (istream &, Time &);
friend ostream &operator << (ostream &, const Time &);
};
Time::Time()
{
hour = 0;
minute = 0;
}
ostream &operator << (ostream &strm, const Worker &obj)
{
strm << obj.fName << " " << obj.lName << " " << obj.payrate;
return strm;
}
istream &operator >>(istream &strm, Worker &obj)
{
strm >> obj.fName;
strm >> obj.lName;
strm >> obj.payrate;
string token;
int h,m;
string t;
for (int i=0; i<token.size(); i++) {
if(token[i]==':')
{
h = atoi (t.c_str());
t.clear();
}
else
{
t=t+token[i];
}
m=atoi(t.c_str());
}
obj.monday1.setHour(h);
obj.monday1.setMinute(m);
return strm;
}
Time Time::operator+ (const Time &right)
{
Time temp;
temp.hour = hour + right.hour;
temp.minute = minute + right.minute;
return temp;
}
int main ()
{
Time time1, time2;
Worker worker[100];
int num;
cout << "Please enter the number of workers on the payrole: ";
cin >> num;
cout << "Please input the worker’s last name, first name, pay rate, start time, and end time from "<< endl;
cout << "Monday through Friday separated by space." << endl;
for (int i=0; i<num; i++)
{
cin >> worker[i];
}
for (int i=0; i<num; i++)
{
cout << worker[i];
}
return 0;
}
In the following block of code, you're using the contents of token and t without having previously initialized their values:
string token;
int h,m;
string t;
for (int i=0; i<token.size();i++){
if(token[i]==':')
{
h = atoi (t.c_str());
t.clear();
}