c++ - 使用带有两个参数的构造函数时出现“调用没有匹配的函数”错误
问题描述
我正在研究 Paul Deitel 的“C++ How to Program”中的教科书问题,我似乎陷入了一个问题。
我们被要求实现一个构造函数DollarAmount
,它接受两个值 (dollars
和cents
) 并将它们作为总硬币存储在一个数据成员amount
中。然后我们被要求用一个简单的程序来测试我们的类。
我的程序如下:
#include <iostream>
#include "DollarAmount.h" // Include the DollarAmount class header file
using namespace std;
int main() {
DollarAmount amount1{1653, 45}; // $1653.45
DollarAmount amount2{123, 6}; // $123.06
cout << "amount1: $" << amount1.toString() << endl;
cout << "amount2: $" << amount2.toString() << endl;
}
我的类头文件是:
#include <string>
#include <cmath>
class DollarAmount {
public:
DollarAmount(int64_t dollars, int cents) {
amount += dollars * 100 + cents;
}
void add(DollarAmount right) {
amount += right.amount;
}
void subtract(DollarAmount right) {
amount -= right.amount;
}
void addInterest(int rate, int divisor) {
DollarAmount interest{
(amount * rate + divisor / 2) / divisor
};
add(interest);
}
std::string toString() const {
std::string dollars{std::to_string(amount / 100)};
std::string cents{std::to_string(std::abs(amount % 100))};
return dollars + "." + (cents.size() == 1 ? "0" : "") + cents;
}
private:
int64_t amount{0};
};
当我的构造函数只接受一个参数时,它工作得很好。但是只要我给它两个参数(dollars
和cents
),我就会得到以下错误:
DollarAmount.h: In member function ‘void DollarAmount::addInterest(int, int)’:
DollarAmount.h:34:9: error: no matching function for call to ‘DollarAmount::DollarAmount(<brace-enclosed initializer list>)’
34 | };
| ^
DollarAmount.h:14:5: note: candidate: ‘DollarAmount::DollarAmount(int64_t, int)’
14 | DollarAmount(int64_t dollars, int cents) { // accepts dollars and cents
| ^~~~~~~~~~~~
DollarAmount.h:14:5: note: candidate expects 2 arguments, 1 provided
DollarAmount.h:12:7: note: candidate: ‘constexpr DollarAmount::DollarAmount(const DollarAmount&)’
12 | class DollarAmount {
| ^~~~~~~~~~~~
DollarAmount.h:12:7: note: no known conversion for argument 1 from ‘int64_t’ {aka ‘long int’} to ‘const DollarAmount&’
DollarAmount.h:12:7: note: candidate: ‘constexpr DollarAmount::DollarAmount(DollarAmount&&)’
DollarAmount.h:12:7: note: no known conversion for argument 1 from ‘int64_t’ {aka ‘long int’} to ‘DollarAmount&&’
我尝试过同时声明dollars
and cents
asint
以及int64_t
(我之所以制作cents
beint
是因为我们只需要一个 0-99 的值)。我还尝试了以下形式的构造函数:
DollarAmount(int64_t dollars, int cents) : amount{dollars * 100 + cents} {}
我不确定为什么它说只提供一个参数,或者如果我尝试使用两个参数,但如果我只使用一个参数,为什么会出现“没有匹配的函数调用”错误。
解决方案
推荐阅读
- plsql - 触发器有问题,它编译得很好,但是在尝试触发时它会出错
- python - 如何解决 Selenium Python 中的 AssertionError?
- java - 在初始化对象本身之前静态变量为空
- javascript - componentDidUpdate 导致无限循环
- node.js - 如何在 Joi 的 valid() 中传递引用
- python - 访问 Django 中帖子的所有内容
- javascript - 为什么我不能在 html 文件中导入 JavaScript 模块?
- javascript - 如何从字符串中自动检测语言
- graphql - 使用 GraphQL 从 GraphCMS 资产中查询特定文件
- postgresql - PostgreSQL - 使用插入功能更新后触发