c++ 在类中调用另一个类

前沿:

在类中可以调用另一个类,作为本类的成员。(我的理解:这个时候,对于类的使用,类似于将类看作一个数据类型。)

示例:
我们有一个点类(Point) 还有一个圆类(circle),我们需要判断点和圆的位置关系(点在圆上,在圆外,在圆内)。我们在Circle类中将Point类作为一个成员使用。

#include <iostream>
#include <math.h>

using namespace std;

class Point
{
public:
    void setx(int p_x)
    {
        x = p_x;
    }
    int getx()
    {
        return x;
    }
    void sety(int p_y)
    {
        y = p_y;
    }
    int gety()
    {
        return y;
    }

private:
    int x;
    int y;
};
class Circle
{
public:
    void setR(int r)
    {
        m_R = r;
    }
    int getR()
    {
        return m_R;
    }
    void setCenter(Point center)
    {
        m_Center = center;
    }
    Point getCenter()
    {
        return m_Center;
    }

private:
    Point m_Center; // the center of the circle is also a Point class
    int m_R;
};

void isInCircle(Circle &c, Point &p)
{
    //  calculate the distance between two points
    double res = pow(pow((c.getCenter().getx() - p.getx()), 2) + pow((c.getCenter().gety() - p.gety()), 2), 0.5);
    if (res == c.getR())
    {
        cout << "the dot is on the circle!" << endl;
    }
    else if (res < c.getR())
    {
        cout << "the dot is within the circle!" << endl;
    }
    else
    {
        cout << "the dot is outside the circle! " << endl;
    }
}

int main()
{
    Circle c;
    c.setR(10);
    Point center;
    center.setx(10);
    center.sety(0);
    c.setCenter(center);

    Point p;
    p.setx(10);
    p.sety(10);

    isInCircle(c, p);
}
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值