【问题标题】:How to operate overload ">>"?如何操作重载“>>”?
【发布时间】:2020-04-06 21:14:02
【问题描述】:
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();

我需要运算符重载&gt;&gt; 吗?我该怎么做?

【问题讨论】:

  • 您不一定需要重载>>,但这是解决上述问题的合理方法。另一种方法是将值读入变量,然后使用您的类设置器设置数据成员。
  • 为什么有这么多指针? Product **products; products = new Product* [numProducts]; products[i] = new Product; 少一个指针Product *products; products = new Product [numProducts]; 代码会更简单。没有理由使用两级指针(实际上甚至没有理由使用一级,但是两级只是过度)。

标签: c++ overloading operator-keyword


【解决方案1】:

我们举一个非常简单的例子,假设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&gt;&gt; 直接读取来自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&gt;&gt;

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&lt;Product&gt; 而不是您自己的数组
  • 如果name 包含空格,则以下示例将不起作用
  • 没有错误检查,operator&gt;&gt; 可能失败

【讨论】:

    【解决方案2】:

    在你的课堂上,写下这个函数

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多