无法在 Class C++ 中重载 + 运算符

Cannot Overload + Operator in Class C++

我正在尝试重载加法运算符。

#pragma once
#include <fstream>
#include <iostream>
class ComplexNumber
{
private:
    int* real;
    int* imag;
public:
    ComplexNumber();
    ~ComplexNumber();
    ComplexNumber(const ComplexNumber&);
    ComplexNumber& operator=(const ComplexNumber&);
    friend std::istream& operator>>(std::istream&, ComplexNumber&);
    friend std::ostream& operator<<(std::ostream&, const ComplexNumber&);
    ComplexNumber operator+(const ComplexNumber&);
    friend ComplexNumber operator-(const ComplexNumber&, const ComplexNumber&);
    ComplexNumber operator* (const ComplexNumber&);
    friend ComplexNumber operator /(const ComplexNumber&, const ComplexNumber&);
};

ComplexNumber::ComplexNumber()
{
    real = new int{ 10 };
    imag = new int{ 10 };
}
ComplexNumber ComplexNumber::operator+(const ComplexNumber& a)
{
    ComplexNumber temp;
    temp.real = this->real + a.real;
    temp.imag = this->imag + a.imag;
    return temp;
    
}

当我尝试编译代码时,它在 a.real 和 a.imag 上给我一个错误,指出表达式必须具有整数或无作用域的枚举类型。这是什么意思?感谢任何提前提供帮助的人。

编辑


std::ostream& operator<<(std::ostream& out, const ComplexNumber& a)
{
    out << *(a.real) << " " << *(a.imag) << "i"; 
    return out;
}

ComplexNumber  aa, ab, ac;
ac = aa + ab;
std::cout << ac << std::endl;

这仍然输出 10 和 10i 而不是 20 和 20i

编辑 2:

ComplexNumber& ComplexNumber::operator=(const ComplexNumber& a)
{
    ComplexNumber temp;
    *(temp.real) = *(a.real);
    *(temp.imag) = *(a.imag);
    return temp;
}

只需通过 * 运算符解除对 real/imag 指针的引用,如下面的代码所示。或者,也许您只需要将它们存储为普通 int(例如 int real;)而不是指向 int.

的指针

Try it online!

#include <fstream>
#include <iostream>

class ComplexNumber
{
private:
    int* real;
    int* imag;
public:
    ComplexNumber();
    ~ComplexNumber() {}
    ComplexNumber(const ComplexNumber&);
    ComplexNumber& operator=(const ComplexNumber&);
    friend std::istream& operator>>(std::istream&, ComplexNumber&);
    friend std::ostream& operator<<(std::ostream&, const ComplexNumber&);
    ComplexNumber operator+(const ComplexNumber&);
    friend ComplexNumber operator-(const ComplexNumber&, const ComplexNumber&);
    ComplexNumber operator* (const ComplexNumber&);
    friend ComplexNumber operator /(const ComplexNumber&, const ComplexNumber&);
};

ComplexNumber::ComplexNumber()
{
    real = new int{ 10 };
    imag = new int{ 10 };
}
ComplexNumber ComplexNumber::operator+(const ComplexNumber& a)
{
    ComplexNumber temp;
    *temp.real = *this->real + *a.real;
    *temp.imag = *this->imag + *a.imag;
    return temp;
    
}
ComplexNumber & ComplexNumber::operator=(const ComplexNumber& a)
{
    *real = *a.real;
    *imag = *a.imag;
    return *this;
    
}
std::ostream& operator<<(std::ostream& out, const ComplexNumber& a)
{
    out << *(a.real) << " " << *(a.imag) << "i"; 
    return out;
}

int main() {
    ComplexNumber aa, ab, ac;
    ac = aa + ab;
    std::cout << ac << std::endl;
    return 0;
}

输出:

20 20i