第一范文网 - 专业文章范例文档资料分享平台

面向对象程序设计实验

来源:用户分享 时间:2025/5/25 10:11:51 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

} 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

搜索更多关于: 面向对象程序设计实验 的文档
面向对象程序设计实验.doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c17wm27o4zv83hrt8bvfx_6.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top