How to operate overload “>>”?

扶醉桌前 提交于 2020-04-14 12:14:23

问题


Product **products;

int numProducts = 0;

void setup()
{
    ifstream finput("products.txt");
    //get # of products first.
    finput >> numProducts;
    products = new Product* [numProducts];

    //get product codes, names & prices.
    for(int i=0; i<numProducts; i++) {
        products[i] = new Product;
        finput >> products[i]->getCode() >> products[i]->getName() >> products[i]->getPrice();
    }
}

I am getting an "invalid operands to binary expression" error for this line:

finput >> products[i]->getCode() >> products[i]->getName() >> products[i]->getPrice();

Do I need to operator overload >> and how would I do it?


回答1:


Let's take a very simple example, assuming a basic definition for Product as:

class Product
{
   int code;
   string name;
   double price;

public:
   Product(int code, const std::string& name, double price)
      : code{code}, name{name}, price{price}
   {}

   int getCode() const { return code; }
   const std::string& getName() const { return name; }
   double getPrice() const { return price; }
};

You can't read in using operator>> directly into the return values from getCode(), getName() or getPrice(). Those are for accessing those values.

Instead, you need to read in the values and construct products from those values like this:

for(int x = 0; x < numProducts; ++x)
{
   int code = 0;
   string name;
   double price = 0;

   finput >> code >> name >> price;
   products[i] = new Product{code,name,price};
}

Now, you could refactor this into operator>>:

std::istream& operator>>(std::istream& in, Product& p)
{
   int code = 0;
   string name;
   double price = 0;

   in >> code >> name >> price;
   p = Product{code,name,price};
   return in;
}

There are a bunch of other things to consider about this code:

  • Use std::vector<Product> instead of your own array
  • The examples below won't work if name has spaces
  • There's no error checking and operator>> can fail



回答2:


In your Class, write down this function

friend ifstream& operator >> (ifstream& in, Product& p1)
{
    in >> p1.code >> p1.name /* ..etc */;

    return in;
}


来源:https://stackoverflow.com/questions/61069078/how-to-operate-overload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!