继承……c++语法

Inheritance... C++ syntax

本文关键字:语法 c++ 继承      更新时间:2023-10-16

我必须创建一个平凡的类,它有几个子类,其中一个子类有自己的子类。

AccountClass.h

#ifndef Account_h
#define Account_h
class Account{
public:
    //Account(){balance = 0.0;}; Here's where the problem was
    Account(double bal=0.0){ balance = bal;};
    double getBal(){return balance;};
protected:
    double balance;
};
#endif

SavingsAccount.h

#ifndef SavingsAccount_h
#define SavingsAccount_h
#include "AccountClass.h"
class SavingsAccount : public Account{
public:
    //SavingsAccount(); And here
    SavingsAccount(double bal = 0.0, int pct = 0.0){ balance = bal; rate = pct; } : Account(bal);
    void compound(){ balance *= rate; };
    void withdraw(double amt){balance -= amt;};
protected:
    double rate;
};
#endif

CheckingAccount.h

#ifndef CheckingAccount_h
#define CheckingAccount_h
#include "AccountClass.h"
class CheckingAccount : public Account{
public:
    //CheckingAccount(); Here also
    CheckingAccount(double bal = 0.0, double lim = 500.0, double chg = 0.5){ balance = bal; limit = lim; charge = chg;} : Account(bal);
    void cash_check(double amt){ balance -= amt;};
protected:
    double limit;
    double charge;
};
#endif

TimeAccount.h

#ifndef TimeAccount_h
#define TimeAccount_h
#include "SavingsAccount.h"
class TimeAccount : public SavingsAccount{
public:
    //TimeAccount(); ;)
    TimeAccount(double bal = 0.0, int pct = 5.0){ balance = bal; rate = pct;} : SavingsAccount(bal,pct);
    void compound(){ funds_avail += (balance * rate); };
    void withdraw(double amt){funds_avail -= amt;};
protected:
    double funds_avail;
};
#endif

我一直得到错误,默认构造函数被定义以及所有不存在的变量…

帮助!

编辑:

修复了预处理器ifndef的

同样,这个问题得到了解决。谢谢@Coincoin !

您没有定义默认构造函数,但是在派生新类时默认调用它们。看起来TimeAccount将是这个问题的罪魁祸首,因为它使用了SavingsAccount的默认构造函数。但是,它们都应该被定义,而不仅仅是声明。

您定义构造函数的方式存在多个错误。

  • 其中一些没有body定义
  • 初始化列表语法上不在正确的位置
  • 您尝试使用默认值参数定义两个默认构造函数。

初始化列表位于签名和主体之间。

一样:

SavingsAccount(double bal = 0.0, int pct = 0.0)
:Account(bal)
{
   balance = bal; rate = pct;
}

另外,您已经有了一个默认构造函数,但是您有一个参数列表,其中所有参数都具有默认值,这意味着您正在尝试定义两个默认构造函数。你要么需要删除bal形参的默认值,要么需要删除默认构造函数,并使用完全默认值的构造函数作为默认构造函数。

一样:

Account(){balance = 0.0;};
Account(double bal){ balance = bal;}

Account(double bal=0.0){ balance = bal;}  

这些:

SavingsAccount();
CheckingAccount();
TimeAccount();

需要有定义,所以:

SavingsAccount(){};
CheckingAccount(){};
TimeAccount(){};

应该

如果构造函数的所有参数都有默认值,编译器如何知道在编写时调用哪些参数:

TimeAccount t;

你可能会看到"模棱两可的函数调用"类型错误。还有,为什么pctTimeAccount()中的int ?默认参数是double,它将该值存储到double类型的字段中。

您需要为所有内容编写默认构造函数。另外,如果需要定义复制构造函数/析构函数/赋值操作符,请确保遵守三规则。

TimeAccount():
  bal(0),
  pct(5.0)
{
}
TimeAccount(double bal, int pct)
{
  balance = bal; 
  rate = pct;
}