using friends

I have no Idea how to fix these errors. It would be cool if someone could assist me.

Here is the code


#include "song.h"

ostream& operator << (ostream& os, Song& obj)
{

os << "title:" << obj.title << " arist:" << obj.artist;
return os;
}
//constructor
Song::Song(string a, string t, int s)
{ // constructor
size = s;
title = t;
strcpy ( title, t );
artist = a;
strcpy ( artist, a );
}
//accessor for name
string Song :: getTitle()
{
return title;
}
//mutator
void Song :: setTitle (string t)
{
name = new string (strlen (t) + 1 );
........

the error

song.cpp: In function `std::ostream& operator<<(std::ostream&, Song&)':
song.h:23: error: `std::string Song::title' is private
song.cpp:6: error: within this context
song.h:24: error: `std::string Song::artist' is private
song.cpp:6: error: within this context
Last edited on
Have you declared

ostream& operator << (ostream& os, Song& obj)

as a friend function of Class Song?

Although the title of the post suggests so, this error can occur if you have declared it as just a global function and trying to access Class Song's pvt members.
Last edited on
Yeah. This is what is in song. h

class Song
{

public:
Song(); // default constructor
Song(string, string, int);
string getArtist();
string getTitle();
int getSize;
void setArtist(string);
void setTitle(string);
void setSize(int);
// friend ostream& operator << (ostream& os, const Song& obj);
friend ostream& operator << (ostream& os, const Song& obj) { os << obj.title << " " << obj.artist; return os; }

private:
string title;
string artist;
int size;

};

You've also implemented operator<< in the header so you should remove it from your .cpp file. Also use inline:

1
2
inline friend ostream& operator<<( ostream& os, const Song& obj )
   { return os << obj.title << " " << obj.artist; }

That worked. Thank you
Topic archived. No new replies allowed.