[英]complex operator overloading
這個復雜的重載功能有什么問題?
#include<iostream.h>
#include<conio.h>
class complex
{
private:
float real,imag;
public:
complex()
{}
complex(float r,float i)
{
real=r;
imag=i;
}
void display()
{
cout<<"the complex is \t"<<real<<"+i."<<imag;
}
complex operator * (complex c1,complex c2)
{
complex t;
t.real=c1.real*real-imag*c1.imag;
t.imag=real*c1.imag+c1.real*imag;
return(t);
}
};
void main()
{
clrscr();
complex c1(4,-5);
complex c2(9,-2);
complex c3;
c3=c1*c2;
c3.display();
getch();
}
這里有幾個問題:
您的operator*
應該在類之外定義(這是一種很好的做法,以支持正確的轉換等操作)。 而不是使用real
和imag
,請使用c2.real
和c2.imag
。
要么使該函數按引用返回,要么實現operator=
(該函數可以在類內部,並且應該僅接收1個參數-rhs)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.