c++ - 过载 ">>"如何操作?

标签 c++ overloading operator-keyword

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();

我是否需要运算符重载>>以及如何做到这一点?

最佳答案

让我们举一个非常简单的例子,假设 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>> 可能失败

关于c++ - 过载 ">>"如何操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61069078/

相关文章:

c++ - 从理论上讲,仅在动态分配中使用内存范围的意外重用来同步线程是否(错误地)合法?

c# - 根据参数值重载方法?

SQL CASE 语句 - 缺少运算符错误

C++ 运算符问题

python - 在python中,如何使正确的操作数在乘以两个不同的类时优先( __rmul__ 方法)?

c++ - 避免此功能的递归

c++ - 如何最有效地对一组球体执行碰撞检测

c++ - 将包含/库目录和链接器参数传播到解决方案中的所有项目?

java - 在继承中使用时与访问修饰符混淆

c++ - 按返回类型重载模板