要访问班内的私人成员?

时间:2019-04-06 17:41:30

标签: c++ class oop private

为什么我们必须先复制然后使用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;
}

1 个答案:

答案 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;
}