简体   繁体   English

为派生类覆盖>>运算符

[英]Overwriting the >> operator for derived classes

I have a program I am working on that requires us to overload the >> for the Employee class so that when it's used it reads in the right type of employee so I have something like this in my main program: 我有一个正在使用的程序,要求我们为Employee类重载>>,以便在使用它时可以读取正确类型的员工,因此我的主程序中具有以下内容:

 Employee *emp;
 empIn >> emp;

I figured the base class is where I would want to do it, because it is the only one that applies to all of the derived classes. 我认为基类是我想做的地方,因为它是唯一适用于所有派生类的类。 The type is determined by an integer at the start of the line so I figured that something like this might work (as I don't know the type until I read it): 该类型由该行开头的整数确定,因此我认为这样的操作可能会起作用(因为在阅读之前我不知道类型):

istream &operator >> (istream &stream, Employee &emp)
{
   int type;
   stream >> type;
   switch(type){
      case 1:
         *emp = new Hourly;
         break;
           ...
   }
   return stream;
}

But, it doesn't work. 但是,它不起作用。 I'm I going about this the right way? 我要以正确的方式进行操作吗? And if not, please point me in the right direction. 如果没有,请指出正确的方向。

The problem, it seems, is that you mix references and pointer. 看来,问题在于您混合了引用和指针。 In the operator>> function, you receive emp as a reference, but access it as a pointer, which is wrong. operator>>函数中,您将emp用作参考,但是将其作为指针访问,这是错误的。

For the whole thing to work, the emp object needs to be allocated before you try to input to it. 为了使整个工作正常进行,在尝试输入emp对象之前,需要对其进行分配。 You can not allocate it inside the function. 您不能在函数内部分配它。

Employe emp;
empIn >> emp;

Or 要么

Employe *emp = new Employe;
empIn >> *emp;

And of course, don't use new inside the function. 当然,不要在函数内部使用new

The compiler should have given you quite a lot of errors for this, you should check out what they say first. 编译器为此会给您带来很多错误,您应该首先检查一下他们所说的内容。

The second argument to your istream function should be Employee* &emp if you want to be able to assign to the pointer as in your example usage. 如果您希望能够像示例用法中那样分配给指针,则istream函数的第二个参数应为Employee* &emp The type would then be a reference to a pointer, which lets you assign it as you want to do instead the method. 然后,该类型将是对指针的引用,该指针使您可以根据需要分配它而不是方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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