【问题标题】:Accessing Protected Members from a QList of Classes eg QList<Account*>从类的 QList 访问受保护的成员,例如 QList<Account*>
【发布时间】: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 classAccount
  • 我不添加 getter 的原因是它没有在给定的 UML 中指定。这就是为什么我试图找到其他使用它的方法。以防我的讲师最终回复我“不,你不能添加额外的吸气剂”。感谢您的建议,我现在将实施它以进行测试。

标签: c++ qt inheritance


【解决方案1】:

我真的不明白为什么你不能为这个protected 数据成员添加一个getter。

但如果您真的不想添加它,您可以按照 @Botje 的建议进行操作。将AccountList 声明为friend of Account。这样,AccountList 将能够访问Accountprivateprotected 成员。

如果不知道怎么做,请在Account的声明中添加friend class AccountList;(假设AccountList已经知道,如果不知道,请转发声明)。

【讨论】:

  • 我不添加另一个 getter 的唯一原因是它没有在作业问题提供的 UML 中给出。我想找到其他访问它的方法,以防讲师回答“不,你不能添加额外的吸气剂”。我会尝试一下朋友的建议,看看是否允许,谢谢你的帮助。
  • @SKYWVRD 是的,也许 UML 中没有指定 getter,因为它们非常隐含,我不知道。但无论如何,friend 方法将按预期工作:)
  • UML 为除那个变量之外的每个变量指定了 getter,这就是为什么我觉得它很奇怪。朋友功能似乎工作得很好:) 谢谢
猜你喜欢
  • 1970-01-01
  • 2014-06-07
  • 2012-12-01
  • 2017-08-01
  • 2016-10-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多