C++ 继承类未正确初始化

标签 c++ constructor

我有一个类 (SavingAccount) 继承自另一个类 (Account)。不知何故,它没有正确初始化。

============================================= =========================

class Account
{
private:
    double balance;

public:
    // constructor
    Account()
    {
        balance = 0;
    }

    Account(double b)
    {
        if (b >= 0)
            balance = b;
        else
        {
            balance = 0;
            cout << "Balance cannot be negative." << endl;
        }
    }
    // destructor
    ~Account()
    {
        // nothing
    }

    // required functions
    bool credit(double a)
    {
        if (a > 0)
        {
            balance += a;
            return true;
        }
        else
        {
            cout << "Credit amount must be greater than 0." << endl;
            return false;
        }
    }

    bool debit(double a)
    {
        if (a > 0 && a <= balance)
        {
            balance -= a;
            return true;
        }
        else if (a > balance)
        {
            cout << "Debit amount exceeded account balance." << endl;
            return false;
        }
    }

    double getBalance()
    {
        return balance;
    }

    void setBalance(double b)
    {
        balance = b;
    }   
};

============================================= =========================

class SavingAccount : public Account
{
private:
    double interestRate;    // percentage

public:
    // constructor
    SavingAccount()
    {
        Account::Account();
        interestRate = 0;
    }

    SavingAccount(double b, double r)
    {
        if (b >= 0 && r >= 0)
        {
            Account::Account(b);
            interestRate = r;
        }
        else
        {
            Account::Account();
            interestRate = 0;
            cout << "Balance or rate cannot be negative." << endl;
        }
    }
    // destructor
    ~SavingAccount()
    {
        // nothing
    }

    // required functions
    double calculateInterest()
    {
        return Account::getBalance() * interestRate / 100;
    }
};

============================================= =========================

我初始化如下:

    SavingAccount acctSaving(2000, 5);

当我跳进去时,acctSaving 显示其余额为 2000。然而,当它到外面时,余额又回到了 0。

如果我改变这一行:

Account::Account(b);

进入:

setBalance(b);

它正确地返回了余额值为 2000 的对象。出了什么问题?第一种方法怎么不对?

最佳答案

Account::Account(b) 并不像您认为的那样。它创建一个类型为 Account 的未命名临时变量,用 b 初始化,然后立即销毁。

您可能正在寻找的是这样的东西:

SavingAccount(double b, double r)
  : Account(b >= 0 && r >= 0 ? b : 0) {
    /* rest of code here */
}

另请参阅:member initializer list

关于C++ 继承类未正确初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848492/

相关文章:

c++ - 如何使控制台库存系统动态化

c++ - 如何在C++中通过引用返回 vector

php - Ruby 语法与 PHP 类构造函数语法?

c++ - 在 C++ 中读取和打印输入和 C 字符串

c++ - sizers 是处理表单的好方法吗?

c++ - 如何在线程中初始化一个对象,然后在其他地方使用它?

C++ 将带有指针的对象添加到 Vector 中

c++ - 关于构造函数调用和继承顺序的一些困惑

c# - 如何判断一个构造函数是否被另一个构造函数调用?

c++ - 解决模板中的循环依赖