【问题标题】:Ambiguous call of overloaded class method重载类方法的模糊调用
【发布时间】:2020-07-05 23:09:39
【问题描述】:

我正在实现一个有理数类。我创建了一个带有参数和所有方法的构造函数。在没有提供参数的情况下,我也尝试添加默认构造函数。

这些是代码的相关部分:

Rational::Rational(int numer, int denom){ //Constructor
    numer = numer;
    denom = denom;
}
Rational::Rational(){
  int numer = 1;
  int denom = 2;
}
#ifndef RATIONAL_H
#define RATIONAL_H

class Rational{
private:
    int numer;
    int denom;

public:
    Rational(int numer=1, int denom=2); // Tried to use this to provide defaults, but still generated errors unless I provided parameters in the Test Driver.
    Rational(); // Tried to make a separate default constructor, also causing errors
    int getNumer();
    int getDenom();
    Rational add(Rational b);
    Rational sub(Rational b); 
    Rational mult(Rational b); 
    Rational divide(Rational b); 
    void setValues(int numer, int denom);
    void print();
    void printFloat();
};


#endif

int main(){
    Rational r(3,4); // Succesfully creates a fraction 3/4
    Rational r1; //causes error

这是尝试创建第二个默认构造函数时生成的错误,我不太确定问题是什么:

错误:重载“Rational()”的调用不明确

【问题讨论】:

    标签: c++ constructor compiler-errors


    【解决方案1】:

    第一个构造函数中的默认参数已经处理了没有给出值的情况。您也不应该创建默认构造函数。删除它,您的代码将编译。

    Rational::Rational(int numer, int denom){
        numer = numer;
        denom = denom;
    }
    Rational::Rational(){
      int numer = 1;
      int denom = 2;
    }
    class Rational{
        Rational(int numer=1, int denom=2);
        Rational();
    };

    您还应该使用初始化列表来初始化构造函数中的变量,而不是赋值语句:

    Rational::Rational(int numer, int denom)
        : numer(numer), denom(denom)
    {
    }
    

    详情见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多