问题
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?
回答1:
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; }
};
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};
}
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:
- 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
回答2:
In your Class, write down this function
friend ifstream& operator >> (ifstream& in, Product& p1)
{
in >> p1.code >> p1.name /* ..etc */;
return in;
}
来源:https://stackoverflow.com/questions/61069078/how-to-operate-overload