Friend Function Confusion.

I am not fully sure on the way that friend functions work and need help fixing/understanding the friend function "printNumbers" in my code.

Header File:
class Date
{
// friend Date printText(Date);
friend Date printNumbers(Date);

public: // Functions available for clients use.

Date(); // Class constructor
void increaseDate(int monthHolder, int dayHolder, int yearHolder);
void insertDate(int monthHolder, int dayHolder, int yearHolder);

private: // Can only be used within the class, Client cannot call it.
int month, day, year;
};

Date.cpp file:
#include <iostream>
#include "Date.h"

Date printNumbers(Date i)
{
std::cout << i.month << " / " << i.day << " / " << i.year << std::endl;
}

client file:
#include <iostream>
#include "Date.h"

using namespace std;

int main()
{
Date a;
int monthHolder, dayHolder, yearHolder, cont;
char printType;

cout << "Input a starting date(ex: 10 1 2009; month day year)." << endl;
cin >> monthHolder >> dayHolder >> yearHolder;

a.insertDate(monthHolder, dayHolder, yearHolder);

cout << "Enter '1' to increase day then 'n' to output number format or 'w'"
<< "to output word format(ex: 1 w or 1 n). To exit enter 0."
<< endl;
cin >> cont >> printType;

while ( cont == 1 )
{
a.increaseDate(monthHolder, dayHolder, yearHolder );

if ( printType == 'n' ){
printNumbers();

}
if( printType == 'w' ){
//printText();

}
else{
cout << "invalid input. Choose 'n' or 'w'." << endl;
}
cout << "continue(1 for yes, 0 for no)?: ";
cin >> cont;
if ( cont == 1 ){
cout << "Choose print format(w or n): ";
cin >> printType;
}
}

return 0;
}

Alright, my goal for this friend function is to print out the values being held in the private section of the Date class in the format of: month / day / year(ex: 10 30 2003). I keep getting errors like i cannot access the int because it is private. There is more to my Date.cpp file but none of it has to do with this problem, so i left it out to make the code shorter. How do i write the friend function so that i can print out the values in the Date.h private section? I have to use a friend function to do this because it is one of the requirements to this project but i cannot seem to figure out how friend functions work.


Last edited on
Mine compiles fine?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A {
  friend void changeX(A&);
  int X;

};


void changeX(A &a) {
  a.X = 5;
}

int main() {

  A myA = A();
  changeX(myA);

  return 0;
}
alright let me make a few changes to match the setup you have. i will let you know if i get any errors or not.
Thank you! got it to work.
No worries :)
Topic archived. No new replies allowed.