Print function for class c++

旧巷老猫 提交于 2019-12-04 02:08:07

If you want to be able to do std::cout << AutoData();, you need to overload the output stream operator operator<<:

std::ostream& operator<< (std::ostream &out, AutoData const& data) {
    out << data.getmpg() << ':';
    out << data.getcylinders() << ':';
    // and so on... 
    return out;
}

This function is not a member function, and since you have getters for each attribute, you do not have to declare this function as friend of your class.

Then you can do:

AutoData myAuto;
std::cout << myAuto << '\n';

What have you tried so far? My approach would be overloading operator<<, like:

std::ostream& operator<<(std::ostream& out, const AutoData& dasAuto) {
  return out << dasAuto.getmpg() << ':' << dasAuto.getcylinders() <<
    /* insert everthing in the desired order here */
    std::endl;
}

And the same thing for the "reading" function, like:

std::istream& operator>>(std::istream& in, AutoData& dasAuto) {
  float mpg;
  int cylinders;
  float displacement;
  float horsepower;
  float weight;
  float acceleration;
  int modelYear;
  int origin;
  string carName;
  char separator;
  const char SEP = ':';

  if( !(in >> mpg >> separator) || (separator != SEP) ) return in;
  if( !(in >> cylinders >> separator) || (separator != SEP) ) return in;
    /* rinse, repeat */
  if( !std::getline(in, carName) ) return in;
  dasAuto.setAuto(mpg, cylinders /*, etc etc */);
  return in;
}

You can read this artical to know about friend and operator <<, http://www.cprogramming.com/tutorial/friends.html

In the class AutoData, you should declare this function:

friend ostream& operator<< (ostream& out, const AutoData& obj); 

outside the class, you should define this function like this:

ostream& operator<< (ostream& out, const AutoData& obj)
{
    out<<obj.mpg<<":";
        //do what you want
    return out;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!