类和对象

来源:互联网 发布:淘宝 药品 线下付款 编辑:程序博客网 时间:2024/05/01 09:22

在程序中同一符号或名字在不同情况下具有不同解释的现象称为多态性

构造函数重载:构造函数可能是C++应用函数重载最多的地方,因为我们设计一个类时总是希望创建对象的同时能以多种方式初始化对象的内部状态,而构造函数只能有一个名字,即该类的名字。

#ifndef COMPLEX_0_0
#define COMPLEX_0_0
/*-------------------------------------------------*/
#include "iostream"
using namespace std;

class COMPLEX
{
private:
 double real;
 double image;
public:
 COMPLEX(double real,double image);//构造函数一,用两个double型数据初始化一个复数对象
 COMPLEX(COMPLEX & other);//构造函数二,用另一个复数对象初始化这个复数对象
 void add(COMPLEX &c);//加法方法,用于例一
 void substract(COMPLEX &c);//减法方法,用于例一
 void print();//输出复数
};
COMPLEX::COMPLEX(double real,double image)
{
 this->real=real;
 this->image=image;
}
COMPLEX::COMPLEX(COMPLEX & other)
{
 this->real=other.real;
 this->image=other.image;
}
void COMPLEX::add(COMPLEX &c)
{
 this->real+=c.real;
 this->image+=c.image;
}
void COMPLEX::substract(COMPLEX &c)
{
 this->real-=c.real;
 this->image-=c.image;
}
void COMPLEX::print()
{
 double temp;

 if(this->real==0 && this->image!=0)
 {
  cout<<"("<<this->image<<"i)";
  return;
 }

 if(this->image>0)
  cout<<"("<<this->real<<"+"<<this->image<<"i"<<")";
 else if(this->image<0)
 {
  temp=-this->image; 
  cout<<"("<<this->real<<"-"<<temp<<"i"<<")";
 }
 else if(this->real==0)
  cout<<"(0)";
 else
  cout<<"("<<this->real<<")";
}
/*-------------------------------------------------*/
#endif

#include "iostream"
#include "complex_1.h"
using namespace std;

void main()
{
 COMPLEX c1(1,2),c2(2,0);//创建一个初值为1+2i的对象c1、创建一个初值为2的对象c2
 COMPLEX c3(c1);//利用c1复数对象创建一个新的对象c3
 system("cls");
 cout<<"c3对象初始值为:";
 c3.print();//首先打印c3对象的值
 cout<<endl;
 cout<<"c2=c2+c1=";
 c2.print();
 cout<<"/t+";
 c1.print();
 cout<<"=";
 c2.add(c1);//将c2加上c1
 c2.print();
 cout<<endl;
 cout<<"c3=c3-c2=";
 c3.print();
 cout<<"/t-";
 c2.print();
 cout<<"=";
 c3.substract(c2);//再将c3减去c2
 c3.print();
 cout<<endl;
 cout<<"c3运算后的值为:";//最后再打印出c3运算后的值
 c3.print();
 cout<<endl;
 system("pause");
 cout<<"谢谢使用,再见!"<<endl;
 system("pause");
 
 return;
}