问题描述
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
这篇关于如何操作过载“"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!