Learning of C++ classes and objects [part1: encapsulation]
Attributes and behavior as a whole
From here, we will explore the topic of classes. The three elements of classes are encapsulation-inheritance-polymorphism.
Let's start with the package.
Refer to the following code:
// arrayone.cpp -- small arrays of integers
#include <iostream>
using namespace std;
const double PI = 3.14;
//要设计一个类
class Circle
{
//访问权限
//公共权限
public:
//属性(通常为变量)
int radius;
//行为(通常为函数)
//获取圆的周长
double calculate()
{
return 2 * PI * radius;
}
};
int main()
{
//通过圆类创建具体对象(实例化)
Circle c1;
//为圆对象属性赋值
c1.radius = 10;
cout << "圆的周长为" << c1.calculate() << endl;
system("pause");
return 0;
}
Here we have created a circle class and calculated its perimeter based on its radius. The code is very simple and will not be repeated.
Professional terms that need attention:
- The attributes and behaviors in the class are collectively called members
- Attribute is also called member attribute member variable
- Behavior is also called member function member method
Why do members of the class like to add an m_ or end with _?
In order to prevent the following situations:
name = name;
Here m is the first letter of member.
Why write behavior first and then properties when defining a class.
In other words, why you don’t need to define variables when you define a class?
access permission
// arrayone.cpp -- small arrays of integers
#include <iostream>
using namespace std;
const double PI = 3.14;
//访问权限
//公共public 保护protected 私有private
//public 类内外均可访问
//protected 仅类内可以访问(子可访问父亲)
//private 仅类内可以访问(子不可访问父亲)
class Person
{
public:
string name_;
protected:
string car_;
private:
int password_;
public:
void func()
{
name_ = "Libo";
car_ = "benz";
password_ = 123;
}
};
int main()
{
Person p1;
p1.name_ = "Jerry";
// p1.car_ = "new";
// p1.password_ = 1234;
p1.func();
system("pause");
return 0;
}
- Public authority public: accessible inside and outside the class
- Protected permissions: Only accessible within the class (child can access the father)
- Private authority private: Only accessible within the class (child cannot access the father)
The difference between struct and class
- struct default public permissions public
- class Default private permissions private