Because B is a subclass of A (do you call it that?), invoking A's stream operator should work. In fact, operator>>(f,a)
in main() works. But for some reason it doesn't work on b casted to A. The error I get is "no matching function for call to 'operator>>(std::basic_istream >&, A)".
What am I doing wrong?
Here is the sample code:
#include <stdlib.h>
#include <fstream>
#include <iostream>
using namespace std;
template <class TypeT>
class A
{
public:
A(){a = -9;}
A(TypeT v){a = v;}
TypeT a;
};
class B : public A<int>
{
public:
B(int w) : A<int>(10) {b = w;}
int b;
};
template <class TypeT>
istream &operator>> (istream &s, A<TypeT> &a)
{
cout << "a.a = " << a.a << endl;
return s;
}
istream &operator>> (istream &s, B &b)
{
cout << "b.b = " << b.b << " ";
operator>>( s, (A<int>)b); // error!
return s;
}
int main(void) {
ifstream f("/dev/null");
A<int> a(0);
operator>>( f, a );
B b(1);
operator>>( f, b );
return EXIT_SUCCESS;
}
.
Change your cast to:
operator>>(s, (A<int> &)b);
Your original cast creates a temporary which you can only get a const reference to.
The problem is that your C-cast is apparently creating a new object rather than upcasting as expected. Since this new object is a temporary it can't be bound to the non-const reference parameter to the parent's operator function. If you static_cast
to a reference to the parent it should work:
operator>>( s, static_cast<A<int>&>(b));
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.