#include<iostream>
using namespace std;
class Person
{
private:
string name; // 默认访问权限是private
int age = 0;
public:
void set_info(string ref_name, int ref_age)
{
name = ref_name;
if (ref_age < 0 || ref_age > 150)
{
cout << "这是个妖怪!" << endl;
return;
}
age = ref_age;
}
void show_info()
{
cout << name << "_" << age << endl;
}
};
void main()
{
Person p1;
p1.set_info("Libai", 180);
p1.show_info();
system("pause");
}
封装-成员变量为类
cpp复制代码
#include<iostream>
using namespace std;
class Point
{
private:
int pos_x;
int pos_y;
public:
void set_info(int ref_x, int ref_y)
{
pos_x = ref_x;
pos_y = ref_y;
}
void get_info(int &x, int& y)
{
x = pos_x;
y = pos_y;
}
};
class Circle
{
private:
Point center;
int radius;
public:
void set_info(Point ref_center, int ref_radius)
{
center = ref_center;
radius = ref_radius;
}
void get_info(int& ret_center_x, int& ret_center_y, int& ret_radius)
{
center.get_info(ret_center_x, ret_center_y);
ret_radius = radius;
}
};
void is_incricle(Circle& c, Point& p)
{
int c_x, c_y, c_r;
c.get_info(c_x, c_y, c_r);
int p_x, p_y;
p.get_info(p_x, p_y);
int dis = (p_x - c_x) * (p_x - c_x) + (p_y - c_y) * (p_y - c_y);
if (dis > (c_r * c_r))
cout << "点在圆外" << endl;
else if (dis == (c_r * c_r))
cout << "点在圆上" << endl;
else
cout << "点在圆内" << endl;
}
void main()
{
Point p1;
p1.set_info(10, 9);
int p_x, p_y;
p1.get_info(p_x, p_y);
cout << "点的坐标是:" << "x=" << p_x << " y=" << p_y << endl;
Point p2;
p2.set_info(10, 0);
Circle c1;
c1.set_info(p2, 10);
int x, y, r;
c1.get_info(x, y, r);
cout << "圆的坐标是:" << "x=" << x << " y=" << y << " r=" << r << endl;
is_incricle(c1, p1);
system("pause");
}
封装-将类置于单独的文件中
cpp复制代码
poin.h文件
#pragma once
#include<iostream>
using namespace std;
// 在头文件中写上成员变量和成员函数的声明即可
class Point
{
private:
int pos_x;
int pos_y;
public:
void set_info(int ref_x, int ref_y);
void get_info(int& x, int& y);
};
cpp复制代码
poin.cpp文件
#include"point.h"
// 所有成员函数的实现放在源文件中,并说明函数的作用域
void Point::set_info(int ref_x, int ref_y)
{
pos_x = ref_x;
pos_y = ref_y;
}
void Point::get_info(int& x, int& y)
{
x = pos_x;
y = pos_y;
}
cpp复制代码
circle.h文件
#pragma once
#include<iostream>
using namespace std;
#include"point.h"
class Circle
{
private:
Point center;
int radius;
public:
void set_info(Point ref_center, int ref_radius);
void get_info(int& ret_center_x, int& ret_center_y, int& ret_radius);
};