더하기 연산자를 오버로드하려고합니다.
#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;
이것은 여전히 20과 20i 대신 10과 10i를 출력합니다.
EDIT2 :
ComplexNumber& ComplexNumber::operator=(const ComplexNumber& a)
{
ComplexNumber temp;
*(temp.real) = *(a.real);
*(temp.imag) = *(a.imag);
return temp;
}
아래 코드와 같이 연산자로 real
/ imag
포인터를 역 참조하십시오 *
. 또는 int에 대한 포인터 대신 일반 int
(예 :)으로 저장해야 할 수도 있습니다 int real;
.
#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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다