在一个类中可以让另一个类作为这个类的成员
#include<iostream>
using namespace std;
class Point//点类
{
public:void setx(int x){c_x = x;}int getx(){return c_x;}void sety(int y){c_y = y;}int gety(){return c_y;}//建议将属性设置为私有,对外提供接口
private:int c_x;int c_y;
};
class Circle//圆类
{
public:void setr(int r){c_R = r;}int getr(){return c_R;}void setcenter(Point center){c_center = center;}Point getcenter()//getcenter()的返回值类型设置为了point类,自己定义的类。{return c_center;}
private:int c_R;Point c_center;//在一个类中可以让另一个类作为这个类的成员
};
//判断
void isInCircle(Circle &c,Point &p)
{int distance =(c.getcenter().getx() - p.getx()) * (c.getcenter().getx() - p.getx()) +(c.getcenter().gety() - p.gety()) * (c.getcenter().gety() - p.gety());int rdistance = c.getr() * c.getr();if (distance == rdistance){cout << "点在圆上" << endl;}else if (distance > rdistance){cout << "点在圆外" << endl;}else{cout << "点在圆内" << endl;}
}
int main(void)
{Circle c;c.setr(10);Point center;//center是圆心这个点center.setx(10);center.sety(10);c.setcenter(center);Point p1;p1.setx(3);p1.sety(4);//调用判断isInCircle(c1, p1);return 0;
}
将一个类拆分成两个文件
point.h
#pragma once
#include<iostream>
using namespace std;
class Point
{
public:void setx(int x);int getx();void sety(int y);int gety();
private:int c_x;int c_y;
};
point.cpp
#include"point.h"
//Point::告诉编译器这是Point作用域下面的一个成员函数
void Point::setx(int x)
{c_x = x;
}
int Point::getx()
{return c_x;
}
void Point::sety(int y)
{Point::c_y = y;
}
int Point::gety()
{return c_y;
}