初始化类函数,但输出仍为 0
initialize class functions but output still 0
我在这个程序上遇到了问题。 当我编译它时,我根据用户输入初始化所有变量,但 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
.您没有注意任何"共享"或"传达"这些数据的方式。
m
、t
、i
都是用随机数据初始化的。与mort1
无关.
我不会在这里详细介绍正确的体系结构是什么,但您应该阅读有关基类初始化的信息。作为提示,我会在您的(有点奇怪)示例中说,您可以尝试使此语法工作:
mPayment m(mort1);
相关文章:
- 如何通过派生类函数更改基类中的向量
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 在类函数中初始化外部作用域变量
- c++ 在非类函数中使用类变量
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- 从类成员函数到类 C 函数指针的转换
- 如何在模板类函数中分配结构值?
- 有没有办法将重载的类函数绑定到函数对象?
- 启动类函数作为失去引用的线程
- C++调用使用重写函数的父类函数
- 将值传递到另一个类函数在打印时为零
- 计算对类函数的所有调用次数
- 由于签名差异,调用了错误的子类函数
- 如何初始化可以设置为默认数组并将输入/输出作为数组的类函数?
- 指针类函数不打印输出
- 初始化类函数,但输出仍为 0
- 类函数中的输出
- 获取定义为父类的子类以输出子函数
- 我的简单类函数中出现意外输出.为什么
- 类函数中的c++字符数组输出