9.2 C++基于对象的程序设计.pptx

9.2C基于对象的程序设计

基于对象的程序设计;目标; double real1,imag1,real2,imag2; cinreal1imag1; cinreal2imag2; coutreal1+real2+imag1+imag2iendl;;struct complex { double real, imag; }; struct complex c1,c2; cinc1.realc1.imag; cinc2.realc2.imag; coutc1.real+c2.real+c1.imag+c2.imagiendl;;void read_complex(struct complex c) { cinc.realc.imag; } void write_complex(const struct complex c) { coutc.real+c.imagiendl; };struct complex add_complex( const struct complex c1, const struct complex c2) { struct complex c; c.real=c1.real+c2.real; c.imag=c1.imag+c2.imag; return c; }; struct complex c1,c2,c3; read_complex(c1); read_complex(c2); c3=add_complex(c1,c2); write_complex(c3);;struct complex { double real, imag; void read_complex(); struct complex add_complex(const struct complex c); void write_complex(); };;void complex::read_complex() { cinrealimag; } void complex::write_complex() { coutreal+imagiendl; };struct complex complex::add_complex(const struct complex c2) { struct complex c; c.real=this-real+c2.real; c.imag=this-imag+c2.imag; return c; }; struct complex c1,c2,c3; c1.read_complex(); c2.read_complex(); c3=c1.add_complex(c2); c3.write_complex();;目标; struct complex c1,c2,c3; cin c1; cin c2; c3=c1 + c2; coutc3;;struct complex { double real, imag; friend ostream operator (ostream,struct complex); friend istream operator (istream,struct complex); struct complex operator+ (const struct complex c2); };;istream operator (istream input,struct complex c) { inputc.realc.imag; return input; } ostream operator (ostream output,struct complex c) { output(c.real,c.imagi); return output; };struct complex complex::operator +(const struct complex c2) { struct complex c; c.real=this-real+c2.real; c.imag=this-imag+c2.imag; return c; };复数 + 整数 (1+2i) + (3) 整数 + 复数 (3) + (1+2i);目标;使用构造函数进行初始化;默认函数+友元函数实现复数混合加法;若实部和虚部是整数时,如何实现复数加法?;类模板---提前声明类和函数模板;类模板---类声明

文档评论(0)

1亿VIP精品文档

相关文档