2
我試圖做一個類以超載+
,-
,*
,/
,<<
,>>
和==
爲了對複數起作用。雖然試圖解決問題,我得到多個錯誤信息,說:操作員在一類超載,導致誤差範圍
error: ‘double complexType::imaginaryPart’ is private
我的頭文件是
#ifndef COMPLEXTYPE_H
#define COMPLEXTYPE_H
#include <iostream>
#include <cmath>
#include <fstream>
class complexType
{
friend ostream& operator << (ostream &os, const complexType &a)
friend istream& operator >> (istream &is, const complexType &a)
public:
complexType();
complexType(double real, double imag);
void getComplexType(double&, double&);
void setComplextType(const double&, const double&);
friend bool operator == (const complexType &otherComplex) const;
friend complexType operator + (const complexType &, const complexType &);
friend complexType operator - (const complexType &, const complexType &);
friend complexType operator * (const complexType &, const complexType &);
friend complexType operator/(const complexType &, const complexType &);
private:
double realPart; //Variable to store the real part
double imaginaryPart; //Variable to store the private part
};
#endif // COMPLEXTYPE_H
和我的執行文件是
#include "complexType.h"
complexType::complexType()
{
realPart = 0.0;
imaginaryPart = 0.0;
}
complexType::complexType(double r, double i)
{
realPart = r;
imaginaryPart = i;
}
void setComplextType(double r, double i)
{
realPart = r;
imaginaryPart = i;
}
bool operator == (const complexType &a, const complexType &b)
{
return (a.realPart == b.realPart && a.imaginaryPart == b.imaginaryPart);
}
operator + (const complexType &a, const complexType &b)
{
complexType temp;
temp.realPart = a.realPart + b.realPart;
temp.imaginaryPart = a.imaginaryPart + b.imaginaryPart;
return temp;
}
operator - (const complexType &a, const complexType &b)
{
complexType temp;
temp.realPart = a.realPart - b.realPart;
temp.imaginaryPart = a.imaginaryPart - b.imaginaryPart;
return temp;
}
operator * (const complexType &a, const complexType &b)
{
complexType temp;
temp.realPart = a.realPart * b.realPart - a.imaginaryPart * b.imaginaryPart;
temp.imaginaryPart = a.realPart * b.imaginaryPart + a.imaginaryPart * b.realpart;
return temp;
}
operator/(const complexType &a, const complexType &b)
{
complexType temp;
temp.realPart = (a.realPart * b.realPart + a.imaginaryPart * b.imaginaryPart)/ (pow(b.realPart,2) + pow(b.imaginaryPart,2));
temp.imaginaryPart = (-a.realPart * b.imaginaryPart + a.imaginaryPart*b.realPart)/(pow(b.realPart,2) + pow(b.imaginaryPart,2));
return temp;
}
ostream & operator << (ostream &os, const complexType &a)
{
os << "(" << a.realPart << " ," << a.imaginaryPart << "i)";
return os;
}
istream & operator >> (istream &is, const complexType &a)
{
char ch, ch2, ch3;
is >> ch;
is >> a.realPart;
is >> ch2;
is >> a.imaginaryPart;
is >> ch3;
return is;
}
我將不勝感激任何幫助,無論是與代碼和格式,因爲這是我的第一個問題。提前致謝。
此外'運算符=='需要刪除'const'並取第二個參數。 –
實際上,那個函數應該是一個類函數。我會以另一種方式去做:不要去做朋友的事情,不要去做它,並相應地實施它。對於在兩邊都有'complexType'的其他運營商也可以這麼說... – paddy
是的我同意,在LHS中定義具有類類型的運算符重載時,避免使用朋友語法,這似乎是OP的模式想用。 –