c++ - 在 C++ 类继承中使用函数

标签 c++ oop inheritance

我正在尝试调用此类中的函数 calculateInterest()

// account.h -- handles banking accounts
#ifndef ACCOUNT_H_
#define ACCOUNT_H_
#include <string>
using std::string;

class Account
{
private:
    double balance;
public:
    Account(double b = 0.0);
    double getBalance() {return balance;}
    void credit(double c);
    void debit(double d); 
};

class SavingsAccount : public Account
{
private:
    double rate;
public:
    SavingsAccount(double r = 0.0);
    double calculateInterest();
};



class CheckingAccount : public Account
{
private:
    double fee;
public:
    CheckingAccount(double f = 0.0);
    void credit(double m);
    void debit(double m);
};


#endif

到目前为止,我可以执行 Account joe(100); 然后使用 Account 类中的函数,所以我显然没有正确继承它。

最佳答案

class Account
{
private:
    double balance;
public:
    Account(double b = 0.0);
    double getBalance() {return balance;}
    void credit(double c);
    void debit(double d);

    // add this!
    virtual double calculateInterest() = 0;
};

您需要在所有派生类中实现 calculateInterest

关于c++ - 在 C++ 类继承中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072084/

相关文章:

c++ - 从现代 C++ 中的命令类型中查找命令处理程序

c++ - 模板 :Function template specializations:Template argument deduction: -->can any one tell some more examples for this statement?

R:何时使用 setGeneric 或在命名空间中导出 s4 方法

c++ - 为什么我不能将命名空间放在父类构造函数调用中?

c++ - 基本深拷贝(操作重载)

c++ - C++ 派生类中的 this 值

c++ - QString 仅替换第一次出现

c++ - C++ 中两个以上集合的 Set_union/Set_intersect

php - (PHP) 从类代码中取消设置一个对象

c# - 大 Switch 语句 : Bad OOP?