C++中成员属性私有化案例(封装)

  • Post author:
  • Post category:其他

有一个要点:要想访问private里的成员可以在public中设置成员接口即可访问

具体代码如下:

#include <iostream>
using namespace std;
#include <string>
class Person
{
public:
	//设置姓名 
	void setName(string name)
	{
		m_Name = name;
	} 
	//获取姓名 
	string getName()
	{
		return m_Name;
	} 
	//设置年龄 
	void setAge(int age)
	{
		if(age<0||age>100)
		{
			cout << "你是喝百岁山长大的嘛!你个码的巴卡!" << endl;
			return;
		}
		m_Age = age;
	} 
	int getAge()
	{
		return m_Age;
	}
	//设置情人 
	void setgirlfriend(string girlfriend)
	{
		m_Girlfriend = girlfriend;
	}
	string getgirlfriend()
	{
		return m_Girlfriend;
	}
//在public里搞几个接口来对private里的元素进行访问 	
private:
	string m_Name;  //可读可写 
	int m_Age;   //只读 
 	string m_Girlfriend; //只写  
};
int main()
{
	system("color f5");
	Person p;
	p.setName("小葵");
	cout << "姓名为:" << p.getName() << endl; 
	p.setAge(20);
	cout << "年龄为:" << p.getAge() << endl; 
	p.setgirlfriend("小七");
	cout << "女朋友为:" << p.getgirlfriend() << endl; 
	system("pause");
	return 0;
}


版权声明:本文为weixin_62539876原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。