云题海 - 专业文章范例文档资料分享平台

当前位置:首页 > 面向对象程序设计实验

面向对象程序设计实验

  • 62 次阅读
  • 3 次下载
  • 2026/4/26 1:58:13

} CComplex(float x, float y) { real = x; imag = y; } CComplex operator + (CComplex &obj1) { CComplex obj2(real + obj1.real, imag + obj1.imag); return obj2; } friend CComplex operator++(CComplex &obj) { obj.real += 1; obj.imag += 1; return obj; } CComplex operator--(); void print() { cout << real << \ } private: float real; float imag; };

CComplex CComplex::operator--() { real -= 1; imag -= 1; return (*this); }

void main() { CComplex obj1(2.1, 3.2); CComplex obj2(3.6, 2.5);

20

cout << \ obj1.print(); cout << \ obj2.print(); CComplex obj3 = obj1 + obj2; cout << \ obj3.print(); ++obj3; cout << \ obj3.print(); --obj3; cout << \ obj3.print(); CComplex obj4 = ++obj3; cout << \ CComplex obj4.print(); }

结果:

obj1=2.1+3.2; obj2=3.1+2.5; obj3=5.7+5.7;

after++obj3=1.7+1.7; after--obj3=5.7+5.7; obj4=1.7+1.7;

7.2.2 程序设计

1.把7.2.1中第一道题的程序改造成采取友元函数重载方式来实现“+”运算符,并采取友元函数重载方式增加前置和后置“++”以及“--”运算符重载,并设计主函数来验证重载运算符的用法。

#include using namespace std; { public: CComplex() { real=0; imag=0;

21

} CComplex(int x,int y) { real=x; imag=y; } friend CComplex operator+(CComplex obj1,CComplex obj2) { return CComplex(obj1.real-obj2.real,obj1.imag-obj2.imag); } friend CComplex operator++(CComplex obj) { obj.real+=1; obj.imag+=1; return(*this); } friend CComplex operator+(CComplex obj1,CComplex obj2) { return CComplex(obj1.real-obj2.real,obj1.imag-obj2.imag); } int real; int imag; }

void show() { cout<

void main() { CComplex obj1(1,2); CComplex obj2(3,4); CComplex obj; obj=obj1+obj2; obj.show(); ++obj; obj.show(); obj=obj1-obj2;

22

}

obj.show(); return 0;

7.3思考题

1.定义CPoint类,有两个成员变量:横坐标(x)和纵坐标(y),对CPoint类重载“++”(自增运算符)、“--”(自减运算符),实现对坐标值的改变。(每个函数均采用友元禾成员函数实现)

#include using namespace std; class CPoint {

public: int x; int y; CPoint() { x=0; y=0; } CPoint(int x,int y) { x=x1; y=y2; } friend CPoint operator++(CPoint obj); { obj.x+=1; obj.y+=1; return (*this); } friend CPoint operator--(CPoint obj); { obj.x-=1; obj.y-=1; return (*this) }

23

int x; int y; }

void show() { cout<<\}

void main() { CPoint obj(1,2); obj.show(); obj++; obj.show(); obj--; obj.show(); return 0; }

24

搜索更多关于: 面向对象程序设计实验 的文档
  • 收藏
  • 违规举报
  • 版权认领
下载文档10.00 元 加入VIP免费下载
推荐下载
本文作者:...

共分享92篇相关文档

文档简介:

} CComplex(float x, float y) { real = x; imag = y; } CComplex operator + (CComplex &obj1) { CComplex obj2(real + obj1.real, imag + obj1.imag); return obj2; } friend CComplex operator++(CComplex &obj) { obj.real += 1; obj.imag += 1; return obj; } CComplex operator--(); void print() { cout << real << \ } private: float real; float imag; }; CComplex C

× 游客快捷下载通道(下载后可以自由复制和排版)
单篇付费下载
限时特价:10 元/份 原价:20元
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:fanwen365 QQ:370150219
Copyright © 云题海 All Rights Reserved. 苏ICP备16052595号-3 网站地图 客服QQ:370150219 邮箱:370150219@qq.com