【发布时间】:2022-01-15 15:44:12
【问题描述】:
#include <iostream>
using namespace std;
class BankDeposit {
int principal;
int years;
float interestRate;
float returnValue;
public:
BankDeposit() { } //This is line number 12
BankDeposit(int p, int y, float r); // r can be a value like 0.04
BankDeposit(int p, int y, int r); // r can be a value like 14
void show();
};
BankDeposit::BankDeposit(int p, int y, float r) {
principal = p;
years = y;
interestRate = r;
returnValue = principal;
for (int i = 0; i < y; i++) {
returnValue = returnValue * (1 + interestRate);
}
}
BankDeposit::BankDeposit(int p, int y, int r) {
principal = p;
years = y;
interestRate = float(r)/100;
returnValue = principal;
for (int i = 0; i < y; i++) {
returnValue = returnValue * (1+interestRate);
}
}
void BankDeposit::show() {
cout << endl << "Principal amount was " << principal
<< ". Return value after " << years
<< " years is "<<returnValue << endl;
}
int main() {
BankDeposit bd1, bd2, bd3;
int p, y;
float r;
int R;
// bd1 = BankDeposit(1, 2, 3);
// bd1.show();
cout << "Enter the value of p y and R" << endl;
cin >> p >> y >> R;
bd2 = BankDeposit(p, y, R);
bd2.show();
return 0;
}
为什么删除或注释掉第 12 行中的代码会导致运行代码出错? 但据我所知,我们正在制作自己的构造函数,那么在代码中需要使用默认构造函数吗?也不在代码中包含默认构造函数是为什么给出错误?
【问题讨论】:
-
BankDeposit bd1, bd2, bd3;需要一个不带参数或具有所有默认参数的构造函数。BankDeposit bd2(p, y, R);可以使用给定的代码。 -
错误是什么?
-
你说错误是在运行代码时,但据我所知,错误是在编译时。代码甚至没有编译,没有什么可运行的。
-
默认 ctor 没有参数。因此,通过使用它,您可以在不向 ctor 传递任何参数的情况下创建对象。就像
BankDeposit bd1;。如果没有默认的ctor,这条语句将不会被编译,你会得到一个错误。
标签: c++ function oop constructor