为什么我们必须先复制然后使用getfunction?为什么我们只能像borrowers.getID() == ID
那样直接使用get函数而不是borrow.getID() == ID
?
我只需要一个解释。我知道可能会遗漏一些东西,但由于效率不高,我对此感到非常困惑!
class ReadershipList {
private:
ifstream myin;
ofstream myout;
string readerfile;
vector<Borrower> borrowers;
public:
int findBorrowerbyID(string ID); //Find the borrowers index by ID
int findBorrowerbyName(string name);
void addBorrower(Borrower newBorrow); //Add a borrower to the vector of borrowers
void listBorrowers(); //Prints the list of borrowers
bool deleteBorrower(string ID); //Delete borrower using ID
Borrower getBorrowerbyID(string ID); /
Borrower getBorrowerbyName(string name); //Get borrower details using name
};
为什么我不能直接访问会员?
而不是使用它:
bool ReadershipList::deleteBorrower(string ID) {
Borrower borrow;
for (int b = 0; b < borrowers.size(); b++) {
borrow = borrowers[b];
if (borrow.getID() == ID) {
borrowers.erase(borrowers.begin() + b);
return true;
}
}
return false;
}
答案 0 :(得分:1)
您不需要复制,可以做到
bool ReadershipList::deleteBorrower(string ID) {
for (int b = 0; b < borrowers.size(); b++) {
if (borrowers[b].getID() == ID) {
borrowers.erase(borrowers.begin() + b);
return true;
}
}
return false;
}
或
bool ReadershipList::deleteBorrower(string ID) {
for (int b = 0; b < borrowers.size(); b++) {
Borrower & borrow = borrowers[b]; // or better "const Borrower & borrow = borrowers[b];" if "string Borrower::getID() const"
if (borrow.getID() == ID) {
borrowers.erase(borrowers.begin() + b);
return true;
}
}
return false;
}