The ingenuity of dark horse programmers-classes and objects

 

C++ has three object-oriented features: encapsulation, inheritance, and polymorphism.

C++ believes that everything in the world is an object, and each object has attributes and behaviors .

Objects with the same attributes are abstracted as classes.

4.1 Package:
4.1.1 Significance of Package

1. Take attributes and behaviors as a whole;

2. Permission control of attributes and behaviors

Attribute, behavior

#include<iostream>
#include<string>
using namespace std;
class student
{
	//属性和行为统称为  成员
	//属性:又称为  成员属性  成员变量
	//行为:又称为  成员函数  成员方法
public:
	//属性
	string name;
	string xvehao;
	//行为
	void print()
	{
		cout << "姓名:" << name << " 学号:" << xvehao << endl;
	}
	void setname(string thename)
	{
		name = thename;
	}
	void setxvehao(string thexvehao)
	{
		xvehao = thexvehao;
	}
};
int main()
{
	string name;
	string xvehao;
	cout << "请输入姓名:" << endl;
	cin >> name;
	cout << "请输入学号:" << endl;
	cin >> xvehao;
	student stu1;//创建一个学生,实例化对象
	//stu1.name = name;
	stu1.setname(name);
	//stu1.xvehao = xvehao;	
	stu1.setxvehao(xvehao);
	stu1.print();
	system("pause");
	return 0;
	
}

Access rights: public, protected, private.

4.1.2 The difference between struct and class

The only difference between struct and class is that by default , struct is a public authority and class is a private authority. 

 

4.1.3 Set member properties to private

 

#include<iostream>
#include<string>
using namespace std;
class person
{
public://通过公共权限控制访问权限
	//写姓名
	void setname(string thename)
	{
		name = thename;
	}
	//读姓名
	string readname()
	{
		return name;
	}
	void setage(int theage)//写权限,检验数据有效性
	{
		if (theage < 0 || theage>150)
		{
			
			cout << "输入年龄有误" << endl;
		}
		else
		{
			age = theage;
		}
	}
	int readage()
	{
		//age = 0;
		return age;
	}
	void setid(string theid)
	{
		id = theid;
	}

private://属性设置为私有
	string name;
	int age;
	string id;
	
};
int main()
{
	person p;
	p.setname("li");
	cout << "姓名为:" << p.readname() << endl;
	p.setage(12);
	cout << "年龄:" << p.readage() << endl;
	p.setid("1111");
	
	system("pause");
	return 0;
	
}

 

Guess you like

Origin blog.csdn.net/yyyllla/article/details/109340647