首页 > 解决方案 > 使用带有两个参数的构造函数时出现“调用没有匹配的函数”错误

问题描述

我正在研究 Paul Deitel 的“C++ How to Program”中的教科书问题,我似乎陷入了一个问题。

我们被要求实现一个构造函数DollarAmount,它接受两个值 (dollarscents) 并将它们作为总硬币存储在一个数据成员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}; 
};

当我的构造函数只接受一个参数时,它工作得很好。但是只要我给它两个参数(dollarscents),我就会得到以下错误:

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&&’

我尝试过同时声明dollarsand centsasint以及int64_t(我之所以制作centsbeint是因为我们只需要一个 0-99 的值)。我还尝试了以下形式的构造函数:

DollarAmount(int64_t dollars, int cents) : amount{dollars * 100 + cents} {}

我不确定为什么它说只提供一个参数,或者如果我尝试使用两个参数,但如果我只使用一个参数,为什么会出现“没有匹配的函数调用”错误。

标签: c++compiler-errors

解决方案


推荐阅读