Xây dựng lớp complex có dạng real+ image*i trong C++

Tạo lớp complex (real + image *i ) có các thành phần sau:
- Các thuộc tính : real , image;
- Hàm tạo có sử dụng tham số mặc định
- Nạp chồng các toán tử sau:
+ Toán tử cộng (+) 
+ Toán tử cộng thành phần real của số phức b lên x (b.real + x)
+ Toán tử trừ (-)
+ Toán tử nhập (>>)
+ Toán tử xuất (<<)

#include <iostream.h>
#include <conio.h>
class complex
{
  private:
    float real,image;
  public:
    complex(float r=0,float i=0);
    complex operator+(complex c);
    complex operator-(complex c);
    friend complex operator+(float x,complex c);
    friend ostream& operator<<(ostream &out,complex c);
    friend istream& operator>>(istream &inp,complex& c);
};
 
complex::complex(float r,float i)
{
   real=r;
   image=i;
}
 
complex complex::operator+(complex c)
{
    complex temp;
    temp.real=real+c.real;
    temp.image=image+c.image;
    return temp;
}
 
complex complex::operator-(complex c)
{
   complex temp;
   temp.real=real-c.real;
   temp.image=image-c.image;
   return temp;
}
 
complex operator+(float x, complex c)
{
   complex temp;
   temp.real=c.real+x;
   temp.image=c.image;
   return temp;
}
 
ostream& operator<<(ostream &out,complex c)
{
   cout<<c.real<<"+"<<c.image<<"i"<<endl;
   return out;
}
 
istream& operator>>(istream &inp,complex &c)
{
  cout<<" Nhap vao phan thuc:";
  cin>>c.real;
  cout<<" Nhap vao phan ao:";
  cin>>c.image;
  return inp;
}
 
void main()
{
    complex c,c1,c2,c3;
    float x;
    cin>>c;
    cin>>c1;
    c2=c+c1;
    cout<<" Cong hai so phuc :"<<c2;
    c3=c1-c;
    cout<<" Tru hai so phuc :"<<c3;
    cout<<" Nhap vao x :";
    cin>>x;
    c3=c3+x;
    cout<< c3;
    getch();
}

Comments

Popular posts from this blog

Khoá luyện thi đại học đảm bảo 2012

10 chiêu tăng tuổi thọ cho pin laptop

Viết bài như thế nào để tốt cho SEO