提问人:Mohammad Maaz 提问时间:11/17/2023 最后编辑:Mohammad Maaz 更新时间:11/17/2023 访问量:82
对构造函数的调用是模棱两可的,构造函数用整数和浮点数重载
Call to constructor is ambigous, constructor overloading with integer & float
问:
我遇到了构造函数重载的问题。在所有代码之后描述问题。
#include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
typedef class BankDeposit {
private:
int interestRate, deposit, years;
float finalAmount, interestAmounts[];
public:
BankDeposit(int deposit, int interestRate, int years);
BankDeposit(int deposit, float interestRate, int years);
void display();
} Deposit;
int main() {
cout << "Hello World!" << endl << endl;
Deposit Deepak(1000, 12, 5);
Deposit Deepika(100, 0.04f, 2);
int deposit;
float interestRate;
int years;
cout << "Enter the deposited amount: ";
cin >> deposit;
cout << "Enter the interest rate: ";
cin >> interestRate;
cout << "Enter the annums of deposition: ";
cin >> years;
cout << endl;
int intInterestRate = interestRate;
Deposit Priya(
deposit,
(intInterestRate < interestRate ? interestRate : intInterestRate), years);
return 0;
}
BankDeposit::BankDeposit(int deposit, int interestRate, int years) {
// BankDeposit::BankDeposit(int deposit, float interestRate, int years) {
// interestRate *= ((int)interestRate < interestRate ? 100 : 1);
this->interestRate = interestRate;
this->deposit = deposit;
this->years = years;
finalAmount = deposit;
for (int i = 0; i < years; i++) {
interestAmounts[i] = finalAmount * interestRate / 100;
finalAmount += interestAmounts[i];
}
display();
}
BankDeposit::BankDeposit(int deposit, float interestRate, int years) {
int intInterestRate = interestRate * 100;
*this = BankDeposit(deposit, intInterestRate, years);
}
void BankDeposit::display() {
cout << "Your final amount'll be: " << finalAmount << endl
<< " Where" << setw(5) << deposit << " was your originial amount"
<< endl
<< " And" << setw(6);
for (int i = 0; i < years; i++) {
cout << interestAmounts[i]
<< (i < years - 2 ? ", "
: i < years - 1 ? " & "
: " ");
}
cout << " are the interestAmounts" << endl
<< " In " << setw(6) << years << " years" << endl
<< endl;
}
Deepika 类传递错误:对构造函数“Deposit”(又名“BankDeposit”)的调用不明确。
Priya 类使用 0.12 作为 interestRate 工作正常,但是当我将 12 作为 interestRate 传递时,它也会将其乘以 100 并给出 100 倍的答案。
特别说明1:我可以简单地使用这一行:
interestRate *= ((int)interestRate < interestRate ? 100 : 1);
并从我的代码中删除了许多垃圾行,但我想根据教程在这里使用构造函数重载。
特别说明 2:3 岁的教程使用 g++ 编译器,而我使用 replit,这可能是他的代码完美运行而我的代码无法正常工作的原因吗?
答: 暂无答案
评论
typedef class BankDeposit { ... } Deposit;
- 获取一本新的 C++ 书籍。你现在使用的那个,当你以后看到“真正的”C++代码时,会让你大吃一惊。0.04
类型为 。因此,有两个匹配的候选项 - 每个候选项都具有隐式转换。可能的修复措施:使用或添加另一个带有参数的构造函数。(但是,我会删除构造函数以防止歧义。double
0.04f
double
int
float finalAmount, interestAmounts[];
BankDeposit(deposit, intInterestRate, years);
*this = BankDeposit(...)