【发布时间】:2020-01-14 00:46:02
【问题描述】:
我正在尝试使用 QT 框架获取存储在 QList 中的帐户列表的总余额。
我的问题是总余额需要从它不允许我访问的类中访问受保护的成员余额。
这个问题来自大学的作业,这个问题已经给了我程序的 UML,并且成员变量 balance 没有 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;
}
我使用 QT Creators IDE 的错误是“totalOfBalances+= at(i)->balance;”上下文中的“double Account::balance' is protected”
【问题讨论】:
-
您要求的是 C++ 语言的
protected关键字的预期工作。是什么阻止您添加 getter 函数或使AccountList成为friend class的Account? -
我不添加 getter 的原因是它没有在给定的 UML 中指定。这就是为什么我试图找到其他使用它的方法。以防我的讲师最终回复我“不,你不能添加额外的吸气剂”。感谢您的建议,我现在将实施它以进行测试。
标签: c++ qt inheritance