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/