(C++学习笔记四)封装的使用

六.封装的使用

1.代码 :

#include<iostream>
using namespace std;

//#define PI 3.1415926
const double PI = 3.1415926;

class Circle//封装一个圆类 其中包含其属性(半径) 行为(计算圆周)
{
public://公共的访问权限 

	int r;
	//属性

	double Perimeter()
	{
		return 2 * PI * r;//圆周
	}
	//行为  获取圆周
};

class Student
{
public://行为
	void s_data(string s_name,int s_num)
	{
		name = s_name;
		num = s_num;
	}

	void display()
	{
		cout << "学生姓名 :" << name << endl
			<< "    学号 :" << num << endl;
	}
public://属性
	string name;
	int num = 0;
};

class Person
{
public://公共权限
	string name;
protected://受保护权限
	string car;
private://私有权限
	int password = 0;
public:
	void func()
	{
		name = "田力";
		car = "奔驰";
		password = 191810;
		cout << "name     =  " << name << endl
			 << "car      =  " << car << endl
			 << "password =  " << password << endl;

	}
};

struct C1
{
	int q = 6;//默认是公共权限
};

class C2
{
	int q = 4;//默认是私有权限
};

class Person1
{
public:
	string name = "德西";//可读可写

	void display_w()
	{
		cout << "请输入解锁密码 :" ;
		cin >> me;
		if (me == 14159)
		{
			cout << endl << "解锁成功" << endl;
			cout << "qname:  " << qname << endl;
			cout << "当前密码:  " << password << endl;
			cout << "输入要修改的密码:  ";
			cin >> me;
			password = me;
			cout << "当前密码:  " << password;
		}
		else cout << endl << "解锁失败" << endl;
	}


	void read_name()
	{
		cout << "name = " << name << endl;
	}

	void write_name(string w_name)
	{
		name = w_name;
		cout << "name = " << name << endl;
	}

	void read_age()
	{
		cout << "age = " << age << endl;
	}

	void write_qname(string w_qname)
	{
		qname = w_qname;
	}

private:
	int age = 20;//只可读不可写

	string qname;//只可写不可读

	int password = 1762;//密码读写

	int me = 0;
};
int main()
{
	Circle c1;
	//通过圆类,创建圆对象
	//c1 就是一个具体的圆

	c1.r = 10;//给圆对象的半径进行赋值操作

	cout << "封装" << endl
		<< "圆周 = " << c1.Perimeter() << endl;
	
	Student stu;
	stu.name = "大海无量";
	stu.num = 181710222;
	stu.display();
	stu.s_data("剑客", 181710000);
	stu.display();

	//-----------访问权限有三种:
	Person p1;
	p1.func();
	p1.name = "小田";
	cout << "name =  " << p1.name << endl;
	//cout << "car =  " << p1.car << endl;//error 不可访问

	//-----------struct和class区别
	C1 dq;
	C2 db;
	cout << "struct C1; dq = " << dq.q << endl;
	//cout << "class  C2; db = " << db.q << endl;//error 不可访问
	
	//----------构建读写权限
	Person1 P11;
	P11.name = "小德";
	cout << "name =  " << P11.name << endl;
	P11.read_age();
	P11.write_name("小小德");
	P11.write_qname("莲");
	P11.display_w();

	system("pause");
	return 0;
}

2.运行结果 :

(C++学习笔记四)封装的使用_第1张图片

你可能感兴趣的:(C++,c++)