[英]Accessing Protected Members from a QList of Classes eg QList<Account*>
我正在嘗試使用QT框架獲取存儲在QList中的帳戶列表的總余額。
我的問題是,總余額需要從我不允許這樣做的類中訪問受保護的成員余額。
這個問題來自大學的作業,這個問題已經給了我程序的UML,並且沒有用於成員變量平衡的getter函數。
我的問題是,有什么方法可以在不使用getter函數的情況下從QList訪問余額。
我嘗試添加新的類指針類型,嘗試直接訪問它,並嘗試創建一個新類,並使用賦值構造函數分配傳遞給它的相關類
class AccountList: public QList<Account*>
{
public:
~AccountList();
bool addAccount(Account* a);
double totalBalance();
void doInterestCalculations();
QString toString() const;
QStringList customersWithHighestPoints() const;
private:
Account* findAccount() const;
};
class Account
{
public:
Account(QString cn, QString an, double ir, QString ty);
Account(const Account & x);
Account& operator=(const Account& x);
QString getCustName() const;
QString getAccNum() const;
QList<Transaction> getTransaction() const;
QString toString() const;
QString getType() const;
double getInterestRate() const;
virtual void transaction(double amt0) = 0;
virtual void calcInterest() = 0;
protected:
double balance;
QList<Transaction> transactions;
private:
QString custName;
QString accNum;
double interestRate;
QString type;
};
double AccountList::totalBalance()
{
double totalOfBalances = 0;
for(int i = 0; i < this->size(); i++)
{
totalOfBalances+= at(i)->balance;
}
return totalOfBalances;
}
在“ totalOfBalances + = at(i)-> balance;”上下文中,我使用QT Creators IDE的錯誤是“ double Account :: balance'受保護”。
我真的不明白為什么您不能為此protected
數據成員添加吸氣劑。
但是,如果您真的不想添加它,可以按照@Botje的建議進行操作。 將AccountList
聲明為Account
friend
。 這樣, AccountList
將能夠訪問Account
的private
成員和protected
成員。
如果您不知道該怎么做,請添加friend class AccountList;
在Account
的聲明中(假設已經知道AccountList
,如果不知道,則進行向前聲明)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.