封装:把属性和方法都进行分装
#include<iostream>
using namespace std;
class MyCircle {
public:
double m_r; // 成员变量
double m_s;
public:
double getR() { // 成员函数
return m_r;
}
double setR(double r) {
m_r = r;
return m_r;
}
double getS() {
m_s = 3.14 * m_r * m_r;
return m_s;
}
};
// 类封装作用
// 类封装了成员变量和成员函数
void PrintCircle01(MyCircle *mp) {
cout << "r is " << mp->getR() << endl;
cout << "s is " << mp->getS() << endl;
}
void PrintCircle02(MyCircle &mp) {
cout << "r is " << mp.getR() << endl;
cout << "s is " << mp.getS() << endl;
}
void PrintCircle03(MyCircle mp) {
}
void main() {
MyCircle c1, c2;
c1.setR(10);
cout << "c1 area: " << c1.getS() << endl;
c1.setR(11);
PrintCircle01(&c1);
c2.setR(20);
PrintCircle02(c2);
}
1 类封装了成员变量和成员函数
2 对属性和方法进行访问控制
3 类的内部和类的外部
4 类的访问关键字
public: 修饰的成员变量和函数,可以在类的内部和类的外部访问
private: 修饰的成员变量和函数,只能在类的内部被访问,不能在类的外部访问
protected:修饰的成员变量和函数,只能在类的内部被访问,不能在类的外部访问,用在继承中子类
class MyAdvCircle {
double m_r2; // 没有权限修饰的成员变量 函数 是私有属性
private:
double m_r; // 成员变量
double m_s;
public:
double getR() { // 成员函数
return m_r;
}
double setR(double r) {
m_r = r;
return m_r;
}
double getS() {
m_s = 3.14 * m_r * m_r;
return m_s;
}
};
void main() {
MyAdvCircle c1, c2;
//c1.m_r = 10; 私有属性不能访问
c1.setR(10); // 外部可以使用
}
与struct的区别
struct AAA{
int a; // 用struct关键字定义的类默认是public 的
public:
protected:
private:
}
struct AAA {
int a = 11;
void printA() {
cout << "a is " << a << endl;
}
};
void main() {
AAA abc;
abc.a = 15; // 可以外部访问a public修饰
abc.printA(); // a is 15
}
164