我一直在创建一个名为Complex的类来存储和处理复数。我遇到的问题是我的重载+和*函数返回了一个非常大的数字,我只能假设它与指针有关,但我很擅长使用它们。我在这里复制了输出:
c1: 1 - i5
c2: -4 + i3
c1 + c2: -9.25596e+061 - i9.255
c1 * c2: -9.25596e+061 - i9.255
Press any key to continue . . .
这是类架构:
// Complex.h
#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
friend std::ostream &operator<<(std::ostream &, const Complex &);
friend std::istream &operator>>(std::istream &, Complex &);
friend Complex &operator+(const Complex &, const Complex &);
friend Complex &operator+(const Complex &, const double &);
friend Complex &operator+(const double &, const Complex &);
friend Complex &operator*(const Complex &, const Complex &);
friend Complex &operator*(const Complex &, const double &);
friend Complex &operator*(const double &, const Complex &);
public:
explicit Complex(double re=0, double im=0);
void setReal(double re);
void setImag(double im);
double &getReal();
double &getImag();
~Complex();
private:
double real;
double imag;
};
在这里,我有我的计划的相关部分:
// Complex.cpp
#include "Complex.h"
ostream &operator<<(ostream &output, const Complex &num)
{
output << num.real << (num.imag >= 0 ? " + i" : " - i") << abs(num.imag);
return output;
}
Complex &operator+(const Complex &num1, const Complex &num2)
{
Complex sum(num1.real + num2.real, num1.imag + num2.imag); // Create new complex by summing elements
return sum;
}
Complex &operator*(const Complex &num1, const Complex &num2)
{
Complex prod(num1.real * num2.real - num1.imag * num2.imag, num1.real * num2.imag + num1.imag * num2.real); // Create new complex by expansion
return prod;
}
Complex::Complex(double re, double im)
{
real = re;
imag = im;
}
int main() {
Complex c1(1.0, -5.0);
Complex c2(-4.0, 3.0);
cout << "c1: " << c1 << endl;
cout << "c2: " << c2 << endl;
cout << "c1 + c2: " << c1 + c2 << endl;
cout << "c1 * c2: " << c1 * c2 << endl;
system("pause");
}
我觉得很难打扰你们。您是否知道一个能够很好地解释C ++概念的站点,如指针,最小特权,多态,继承等?
很抱歉在这里提出基本问题,但很难找到解释这些内容的资源。
答案 0 :(得分:1)
问题是大多数重载运算符都返回对本地var的引用,当操作符函数返回时会被销毁,从而留下悬空引用。尝试更改您的运算符以返回Complex
而不是Complex &
:
Complex operator+(const Complex &num1, const Complex &num2)
{
Complex sum(num1.real + num2.real, num1.imag + num2.imag); // Create new complex by summing elements
return sum;
}
答案 1 :(得分:1)
错误的退货类型:
Complex &operator+(const Complex &num1, const Complex &num2)
^^^^^^^^^
您正在创建一个临时Complex
并通过引用返回它,然后它会被销毁,因此您有一个悬空引用。由于operator+
正在构建一个新对象并返回它,它应该通过 value 返回它...所以签名应该是:
Complex operator+(Complex const&, Complex const& );