如何操作过载“"? [英] How to operate overload ">>"?

查看:102
本文介绍了如何操作过载“"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

让我们举一个非常简单的示例,假设Product的基本定义为:

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; }
};

您不能直接使用operator>>读入getCode()getName()getPrice()的返回值中.这些用于访问这些值.

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};
}

现在,您可以将其重构为operator>>:

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:

  • 使用std::vector<Product>而不是您自己的数组
  • 如果name有空格,以下示例将不起作用
  • 没有错误检查,operator>> 可以失败
  • 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

这篇关于如何操作过载“"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆