gpt4 book ai didi

java - 找不到合适的构造函数 (Java)

转载 作者:行者123 更新时间:2023-11-29 03:02:11 25 4
gpt4 key购买 nike

我正在尝试在这里编译我的程序,但我遇到了一个小错误,错误是“没有找到适合 ComplexNumber(double) 的构造函数。”到目前为止,这是我的代码。

public class ComplexNumber extends ImaginaryNumber
{
private double realCoefficient;

public ComplexNumber ( )
{
super ( );
this.realCoefficient = 1;
}

public ComplexNumber (double r, double i)
{
super (i);
this.realCoefficient = r;
}

public ComplexNumber add (ComplexNumber another)
{
return new ComplexNumber (this.realCoefficient + another.realCoefficient); //the error at complile occurs here, right at new.
}//More Codes

我遇到过一次这个问题,那是因为我没有参数化的构造函数。然而这一次,我有一个。所以我不知道这次是什么问题。

这是我的 ImaginaryNumber 代码

public class ImaginaryNumber implements ImaginaryInterface
{
//Declaring a variable.
protected double coefficient;

//Default constructor.
public ImaginaryNumber( )
{
this.coefficient = 1;
}

//Parameterized constructor.
public ImaginaryNumber(double number)
{
this.coefficient = number;
}

//Adding and returing an imaginary number.
public ImaginaryNumber add (ImaginaryNumber another)
{
return new ImaginaryNumber(this.coefficient + another.coefficient);
}//More Codes

我的 ImaginaryNumber 类工作正常。

最佳答案

add 方法中,您试图将一个参数传递给构造函数,但您只有带有 0 个或 2 个参数的构造函数。

看起来您无论如何都需要添加 ComplexNumber 的虚部,因此将虚部添加作为构造函数的第二个参数。

使用 Imaginary 中的 coefficient 保护变量:

return new ComplexNumber (this.realCoefficient + another.realCoefficient,
this.coefficient + another.coefficient);

关于java - 找不到合适的构造函数 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com