#include<iostream> #include<cmath> #include<string.h> using namespace std; class myComplex{ private: double real; double imag; public: myComplex(); ~myComplex(){} myComplex(int a){ real = a; } myComplex(int a, int b){ real = a; imag = b;} myComplex(myComplex& v){ real = v.real; imag = v.imag; } double getReal(){ return this->real;} //返回复数的实部 double getImaginary(){ return this->imag; } //返回复数的虚部 //返回复数的模 double getModulus(myComplex &num){ double temp; temp = sqrt(num.real*num.real + num.imag*num.imag); return temp; } //类对象的赋值 myComplex& operator=(myComplex& rhs){ imag = rhs.imag; real = rhs.imag; return *this; } //重载+=运算符 myComplex& operator+=(myComplex& rhs){ real = real + rhs.real; imag = imag + rhs.real; return *this; } //重载-=运算符 myComplex& operator-=(myComplex& rhs){ real = real - rhs.real; imag = imag -rhs.real; return *this; } //重载*=运算符 myComplex& operator*=(myComplex& rhs){ real = real * rhs.real; imag = imag * rhs.real; return *this; } //重载/=运算符 myComplex& operator/=(myComplex& rhs){ real = real / rhs.real; imag = imag /rhs.real; return *this; } //重载+运算符 friend myComplex operator+(myComplex m, myComplex n){ myComplex temp; temp.real = m.real+n.real; temp.imag = m.imag + n.imag; return temp; } //重载-运算符 friend myComplex operator-(myComplex m, myComplex n){ myComplex temp; temp.real = m.real - n.real; temp.imag = m.imag -n.imag; return temp; } //重载*运算符 friend myComplex operator*(myComplex m, myComplex n){ myComplex temp; temp.real = m.real*n.real - m.imag*n.imag; temp.imag = m.imag*n.real + m.real*n.imag; return temp; } //重载/运算符 friend myComplex operator/(myComplex m, myComplex n){ myComplex temp; temp.real = (m.real*n.real + m.imag*n.imag) / (n.real*n.real+n.imag*n.imag); temp.imag = (m.imag*n.real -m.real*n.imag) / (n.real*n.real + n.imag*n.imag); return temp; } //重载<<运算符 friend ostream& operator<<(ostream &os, myComplex c){ os << '(' << c.real << ',' << c.imag << ')'; return os; } //重载>>运算符 friend istream& operator>>(istream& is, myComplex& c){ is >> c.real >> c.imag; return is; } };
cpp文件
#include<iostream> #include<cmath> #include<string.h> #include"mycomplex.h" using namespace std; int main(){ myComplex c1; myComplex c2; cin >> c1 >> c2; c2 = c1; cout << c1 << endl; cout << c2 << endl; cout << c1 + c2 << endl; cout << c1 - c2 << endl; cout << c1 / c2 << endl; cout << c1 * c2 << endl; return 0; }
错误截图:
感谢您的回答和帮助。
或者改为改为myComplex(): real(0.0f),imag(0.0f){};默认初始化为0.0,就更好了。谢谢您,问题已得到解决。
似乎是因为你的myComplex();没有定义。改为myComplex(){};应该可以通过编译。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。