C++实验二

来源:互联网 发布:淘宝商家怎么进天猫 编辑:程序博客网 时间:2024/06/16 01:21

在实验一的基础上:

加一个常成员函数;

用对象数组初始化两个人的坐标,然后用友元函数求出距离并输出;

#include <iostream>
#include <cmath>


using namespace std;




class point
{
public:
    point(int my_x, int my_y, int my_z);
    point()
    {
        x = 0;
        y = 0;
        z = 0;
    }
    void tellmeyourpoint(int your_x = 1, int your_y = 1, int your_z = 1);
    friend double ourdistance(point &p1, point &p2);//定义友元函数
    void showpoint()
    {
        cout<<x<<","<<y<<","<<z<<endl;
    }
    void cshowpoint() const;//定义常成员函数
    ~point()
    {
        cout<<"OK"<<endl;
    }
private:
    int x;
    int y;
    int z;
};
void point::cshowpoint() const
{
    cout<<x<<"! "<<y<<"! "<<z<<endl;
}
point::point(int my_x, int my_y, int my_z)
{
    x = my_x;
    y = my_y;
    z = my_z;
}
void point::tellmeyourpoint(int your_x, int your_y, int your_z)
{
    x = your_x;
    y = your_y;
    z = your_z;
}
double ourdistance(point &p1, point &p2)//友元函数计算距离
{
    double x = p1.x - p2.x;
    double y = p1.y - p2.y;
    double z = p1.z - p2.z;
    return static_cast<double>(sqrt(x * x + y * y + z * z));
}
int main()
{
    point P(6, 6, 6);
    P.showpoint();//P调用有参构造函数
    point PP;
    PP.showpoint();//PP调用无参构造函数
    int yx, yy, yz;
    cin>>yx>>yy>>yz;
    P.tellmeyourpoint(yx, yy, yz);
    P.showpoint();
    const point cp(1, 2, 3);//常成员函数
    cp.cshowpoint();//调用常成员函数
    point dis[2] = {
        point(1, 1, 1),
        point(2, 2, 2)
    };//对象数组初始化
    cout<<"our distance :"<<endl;
    cout<<ourdistance(dis[0], dis[1])<<endl;
    return 0;
}

原创粉丝点击