friend function

how to access private

Page 1 of 1

3 Replies - 2012 Views - Last Post: 10 December 2006 - 10:02 AM Rate Topic: -----

#1 jrjan1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 08-December 06

friend function

Posted 08 December 2006 - 09:02 PM

I think I need to access the private data members, so I wrote a friend function, but it's not working the way I thought it was supposed to. Can someone help?

this is my header file
class Item
{
friend ostream& operator<<(ostream&, Item& );

public:
void print() const;
Item(string* p, string* d, double* pr);
Item();

private:
string* part;
string* deptNo;
double* itemPrice;
};

Item::Item(string* p, string* d, double* pr)
{
part = p;
deptNo = d;
itemPrice = pr;
}

Item::Item()
{}

ostream& operator<<(ostream& osObject, Item& i)
{
osObject<<i.part;
osObject<<" ";
osObject<<i.deptNo;
osObject<<" ";
osObject<<i.itemPrice<<endl;
return osObject;
}

This is in the other .cpp file in the main(). If I can't put these couts here because they are private, how can I write this. I eventually need to sort the part, deptNo and itemPrice.

while (!inData.eof())
{
// read a line of data from the inData file,
// and store the data in the local variables
// partNum, dept, price

readDataItem(inData, partNum, dept, price);

Item *list = new Item[i];

cout<<list->part;
cout<<list->deptNo;
cout<<list->itemPrice;

}

Is This A Good Question/Topic? 0
  • +

Replies To: friend function

#2 Xing  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 19
  • View blog
  • Posts: 725
  • Joined: 22-July 06

Re: friend function

Posted 08 December 2006 - 09:20 PM

What do you mean it's not working?
Is it giving you an error? or wrong output? What output did you expected?
Your while loop has problem and please use code tags while posting codes.
Was This Post Helpful? 0
  • +
  • -

#3 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 291
  • View blog
  • Posts: 1,900
  • Joined: 25-October 06

Re: friend function

Posted 09 December 2006 - 12:45 AM

clearly you have a problem with statements such as
cout<<list->part;
cout<<list->deptNo;
cout<<list->itemPrice;


because part, deptNo and itemPrice are private data members of Item and you cannot access them

however, you should be able to use the overloaded friend function operator<<(), e.g.
cout << *list;


This post has been edited by horace: 09 December 2006 - 12:46 AM

Was This Post Helpful? 0
  • +
  • -

#4 jrjan1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 08-December 06

Re: friend function

Post icon  Posted 10 December 2006 - 10:02 AM

I just don't understand how to get the individual arrays so I can sort them. If I cout<<*list, i get it looks like references, and list[i] doesn't give me anything. How can I get 3 separate arrays so I can sort them?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1