简体   繁体   中英

How to use cust or pointers in stream operator overloading function?

I have parent and child classes. Both of them are overloading >> operator. I need to read from a file(or screen) to parent object and then cast it to child (or use pointers). Right now I'm using sets and gets.

ifstream& operator>>(ifstream& ifs, Child& ch)
{
    Parent p;       
    ifs >> ch.field >> p;
    ch.setCh(p);
    return(ifs);
}

void Ch::setCh(Parent pIn){setField1(pIn.getField1());}

One possible solution can be seen in this example:

#include <iostream>
using namespace std;

class A {
 public:
  int val;
  friend istream& operator>>(istream& in, A& a);
};

istream& operator>>(istream& in, A& a) {
 cout << "Calling a::>>\n";
 in >> a.val;
 return in;
}

class B : public A {
 public:
  int val2;
  friend istream& operator>>(istream& in, B& b);
};

istream& operator>>(istream& in, B& b) {
  cout << "Calling b::>>\n";
  in >> static_cast<A&>(b);
  in >> b.val2;
  return in;
}
int main(int argc, char** argv) {
  B b;
  cin >> b;
  cout << b.val << " " << b.val2 << endl;
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM