直接看题吧:
输入圆的半径和圆柱的高,依次输出圆周长、圆面积、圆柱体积(π取 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; }
关于友元函数: