Link to home
Start Free TrialLog in
Avatar of ee-user
ee-user

asked on

STL string, iostream, and cout of class info

I'm an STL newbie, and I'm tring to write a simple program to cout a class that has an std::string in it

Here's a program that works but that doesn't use stl:

// *** compile with cl -GX test00.cpp
#include <iostream.h>
#include <string.h>

class CInfo
{
public:
  CInfo(int key, char* ref);

  friend ostream& operator<<(ostream& s, const CInfo &info);

private:
  int   m_key;
  char  m_ref[20];
};

CInfo::CInfo(int key, char* ref) : m_key(key) { strcpy(m_ref, ref); }

ostream& operator<<(ostream& s, const CInfo &info)
{
  return s << '(' << info.m_ref << ')';
}

int main(void)
{
  cout << "Reached main" << endl;
  CInfo myInfo(123456, "myRef");
  cout << myInfo << endl;
  return 0;
}


Here's the (roughly equivalent) program with std::string.  There's some strangeness with std::ostream, and I get the compiler error for the cout << myInfo << endl;

error C2678: binary '<<' : no operator defined which takes a left-hand operand of type 'class ostream_withassign' (or there is no acceptable conversion)

// *** compile with cl -GX test01.cpp
#include <iostream.h>
#include <string.h>

class CInfo
{
public:
  CInfo(int key, char* ref);

  friend ostream& operator<<(ostream& s, const CInfo &info);

private:
  int   m_key;
  char  m_ref[20];
};

CInfo::CInfo(int key, char* ref) : m_key(key) { strcpy(m_ref, ref); }

ostream& operator<<(ostream& s, const CInfo &info)
{
  return s << '(' << info.m_ref << ')';
}

int main(void)
{
  cout << "Reached main" << endl;
  CInfo myInfo(123456, "myRef");
  cout << myInfo << endl;   // <-- causes compiler error
  return 0;
}

What am I doing incorrectly?  And is the std::outstream necessary?  

TIA
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ee-user
ee-user

ASKER

duhhhh ...
thx