gpt4 book ai didi

c++ - 复数类C++的主要功能

转载 作者:太空宇宙 更新时间:2023-11-04 15:17:54 24 4
gpt4 key购买 nike

我正在为 C++ 做作业,我对这门语言还很陌生。该作业是关于为具有复数根的函数实现牛顿拉夫森方法。我已经实现了代码。

我现在想测试我的代码,但我很难让我的主要功能正常工作,有一些我不理解的概念导致我错误的实现。我将不胜感激一些解释,以便我能更好地理解。谢谢。

这是我的代码示例:

复杂.h

#include<iostream>
#include<cmath>

using namespace std;

class Complex {
private:
double r;
double i;

public:
Complex(double real, double imaginary);
friend Complex operator+(const Complex& c1, const Complex& c2);
friend ostream& operator<<(ostream& outs, const Complex& number);
};

复杂.cpp

#include "testComplex.h"

Complex::Complex(double real = 0.0, double imaginary = 0.0) : r(real), i(imaginary) {}
Complex operator+(const Complex& c1, const Complex& c2) {
Complex result;
result.r = c1.r + c2.r;
result.i = c1.i + c2.i;
return result;
}

主要.cpp

#include <iostream>
#include "testComplex.h"

using namespace std;

int main () {
Complex x;
Complex y;
Complex sum;
x = Complex(2, 4);
y = Complex(3, 0);
sum = x + y;
cout << "The sum (x + y) is: " << sum << endl;
return 0;
}

这是我收到的错误的一部分:

testComplexmain.cc: In function ‘int main()’:
testComplexmain.cc:8:10: error: no matching function for call to ‘Complex::Complex()’
testComplexmain.cc:8:10: note: candidates are:
testComplex.h:15:2: note: Complex::Complex(double, double)
testComplex.h:15:2: note: candidate expects 2 arguments, 0 provided
testComplex.h:8:7: note: Complex::Complex(const Complex&)
testComplex.h:8:7: note: candidate expects 1 argument, 0 provided
testComplexmain.cc:9:10: error: no matching function for call to ‘Complex::Complex()’

最佳答案

您没有默认构造函数。双参数构造函数可以作为一个参数使用,因为两个参数都是可选的;但是您必须将默认参数放在 header 中的声明中,而不是源文件中的定义中,以便它们可以从 main 中使用。

就个人而言,我会使用 std::complex 而不是重新发明它。

关于c++ - 复数类C++的主要功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27529351/

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