C++面向对象总结——类的实践
2021/7/29 14:05:57
本文主要是介绍C++面向对象总结——类的实践,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
直接看题吧:
第一题
输入圆的半径和圆柱的高,依次输出圆周长、圆面积、圆柱体积(π取 3.14)。
#include<iostream> using namespace std; class cylinder { public: cylinder() :PI(3.14) { cout << "请输入半径" << endl; cin >> cyl_radius; cout << "请输入高" << endl; cin >> cyl_height; } void cyl_out() { cout << "圆柱的体积:" << PI * cyl_radius * cyl_radius * cyl_height << endl; cout << "圆的面积:" << PI * cyl_radius * cyl_radius << endl; cout << "圆的周长:" << PI * cyl_radius * 2 << endl; } protected: const double PI; double cyl_radius; double cyl_height; }; int main() { cylinder cyl; cyl.cyl_out(); return 0; }
需要注意到的是const 修饰的类的成员,它的初始化只能采用构造函数(初始化列表)的方式,这里也可以不使用这种方式,在这里仅仅只是为了学习const以及构造函数。
第二题
定义一个 Point 类,其属性包括点的坐标,提供计算两点之间距离的方法.
这题使用类的友元函数访问类的私有成员。
#include<iostream> using namespace std; class Point { public: Point(string m = "") { cout << "输入" << m << "点的x坐标" << endl; cin >> x; cout << "输入" << m << "点的y坐标" << endl; cin >> y; cout << m << "点的坐标为(" << x << "," << y << ")" << endl; } friend double distance(Point& A, Point& B) { double distance_hor = A.x - B.x; double distance_ver = A.y - B.y; double distance_pt = sqrt(distance_hor * distance_hor + distance_ver * distance_ver); return distance_pt; } private: double x; double y; }; int main() { Point A("A"); Point B("B"); cout << "两点间的距离:" << distance(A, B) << endl; }
关于友元函数:
这篇关于C++面向对象总结——类的实践的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-03微信支付提示下单账户与支付账户不一致-icode9专业技术文章分享
- 2024-07-03微信支付提示订单号重复-icode9专业技术文章分享
- 2024-07-02微服务启动nacos注册上去了,但是一直没有收到请求-icode9专业技术文章分享
- 2024-07-02如何检查文件的编码格式-icode9专业技术文章分享
- 2024-07-02sublime 更改编码格式-icode9专业技术文章分享
- 2024-06-30uniAPP 实现全屏左右滚动滚动的效果-icode9专业技术文章分享
- 2024-06-30如何在本地使用授权或插件-icode9专业技术文章分享
- 2024-06-30伪静态规则配置方法汇总-icode9专业技术文章分享
- 2024-06-29易优CMS安装常见问题汇总-icode9专业技术文章分享
- 2024-06-28易优新手必读安装教程-icode9专业技术文章分享