【发布时间】:2021-02-17 19:52:12
【问题描述】:
我正在尝试重载加法运算符。
#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
EDIT2:
ComplexNumber& ComplexNumber::operator=(const ComplexNumber& a)
{
ComplexNumber temp;
*(temp.real) = *(a.real);
*(temp.imag) = *(a.imag);
return temp;
}
【问题讨论】:
-
为什么
real和imag的类型是int*而不是int类型? -
我的教授向我们提供了头文件,我们必须实现它。这是唯一的原因哈哈
-
你能发布你对
operator=的实现吗? -
是的,我刚刚添加了它。感谢您的帮助
-
@ZachSal 你在做
operator=时不应该使用temp,你需要通过*this->real = *a.real;分配给当前对象。看at my answer。
标签: c++ class dynamic operator-overloading