如何操作过载“ >>”?

问题描述 投票:1回答:2
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();
    }
}

此行出现“对二进制表达式无效的操作数”错误:

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

我是否需要操作员重载>>,我该怎么办?

c++ overloading operator-keyword
2个回答
2
投票

在您的课堂上,记下此功能

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

    return in;
}

0
投票

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

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()的返回值。这些用于访问这些值。

相反,您需要读入值并从这些值构造产品,如下所示:

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

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

关于此代码,还有很多其他事情要考虑:

  • 使用std::vector<Product>而不是您自己的数组
  • 如果name有空格,以下示例将不起作用
  • 没有错误检查,operator>> 可以失败
© www.soinside.com 2019 - 2024. All rights reserved.