初始化类函数,但输出仍为 0

initialize class functions but output still 0

本文关键字:输出 类函数 初始化      更新时间:2023-10-16

我在这个程序上遇到了问题。 当我编译它时,我根据用户输入初始化所有变量,但 cout 仍然显示大多数语句的问题为"0",其中一个语句为"负"数。 有什么想法吗?

#include <iostream>
#include <conio.h>
#include <cmath>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
protected:
    float term;
public:
    void setData(float, float, float);
    float setTerm ();
    float monthly;
    float total;
    float interest;
    int years;
    float loan;
};
void MortgageCalc::setData(float l, float i, float y)
{
   loan = l;
   interest = i;
   years = y;
   setTerm();
}
float MortgageCalc::setTerm()
{  //simple interest calculation with power calc to establish whole number translation
     term = pow((1 + ((interest/100) / 12)), (12 * years));
     return term;
}
class mPayment : public MortgageCalc
{
public:
    int monthly()
    {
        return ((loan * ((interest/100) / 12) * term ) / (term - 1));
    }
};
class tPayment : public mPayment
{
public:
    int total()
    {
        return (monthly() * (years * 12));
    }
};
class iPayment : public tPayment
{
public:
    int plusInterest()
    {
        return (total() - loan);
    }
};
int main()
{
double loan(0), interest(0);
int years = 0;
MortgageCalc mort1;
    cout << "Enter the total loan amount on your mortgage loan: $";  //established loan variable
        cin >> loan;
    cout << "Enter the interest rate (in whole #'s only): ";  //establishes interest rate variable
        cin >> interest;
    cout << "Enter the length of the loan in years: "; //establishes term of payments
        cin >> years;
mort1.setData(loan, interest, years);
mPayment m;
       cout << "Monthly payment due is " << m.monthly() << "." << endl;
tPayment t;
        cout << "Total payment will be " << t.total() << "." << endl;
iPayment i;
        cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
return 0;
};

您正在获取所有不同的对象,例如MortgageCalc mort1; mPayment m; tPayment t; iPayment i;.这些对象没有任何关系。

例:

mort1 = {term, monthly, total, interest, years, loan}  

假设您已经初始化为 1

mort1 = {term=1, monthly=1, total=1, interest=1, years=1, loan=1}

但它不会影响 M,因为两者都存储在不同位置的内存中。

m = {term=0, monthly=0, total=0, interest=0, years=0, loan=0}  

您可以检查两者具有不同的基址,例如cout<<&mort1<<endl<<&m;

您设置的数据成员是 MortgageCalc mort1 的一部分,而不是 mPayment m; tPayment t; 的一部分。

你需要复习你的C++基本款。

在这些行上使用默认构造函数:

mPayment m;
tPayment t;
iPayment i;

他们没有以前输入的数据的概念,mort1 .您没有注意任何"共享"或"传达"这些数据的方式。

mti都是用随机数据初始化的。与mort1无关.

我不会在这里详细介绍正确的体系结构是什么,但您应该阅读有关基类初始化的信息。作为提示,我会在您的(有点奇怪)示例中说,您可以尝试使此语法工作:

mPayment m(mort1);