脚本宝典收集整理的这篇文章主要介绍了【C++】 15_类于封装的概念,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
类的组合
电脑一般而言是由 CPU, 内存,主板,键盘和硬盘等部件组合而成。
思考:
类的封装
-
类通常分为以下两个部分
- 类的实现细节
- 类的使用方式
- 当使用类时,不需要关心其实现细节
- 当创建类时,才需要考虑其内部实现细节
例:
封装的基本概念
C++ 中类的封装
编程实验: 类成员的访问属性
@H_530_126@
#include <stdio.h>
struct Biology {
bool living;
};
struct Animal : Biology {
bool movable;
void foidFood() { };
};
struct Plant : Biology {
bool growable;
};
struct Beast : Animal {
void sleep() { };
};
struct Human : Animal {
void sleep() { };
void work() { };
};
struct Girl : Human
{
private:
int age;
int weight;
public:
void print()
{
age = 22;
weight = 48;
printf("I am a girl, I am %d years old.n", age);
printf("My weight is %d kg.n", age);
}
};
struct Boy : Human
{
private:
int height;
int salary;
public:
int age;
int weight;
void print()
{
height = 175;
salary = 9000;
printf("I am a boy, my height is %d cm.n", height);
printf("My salary is %d RMB.n", salary);
}
};
int main()
{
Girl g;
Boy b;
g.print();
b.age = 19;
b.weight = 120;
b.print();
return 0;
}
输出:
I am a girl, I am 22 years old.
My weight is 22 kg.
I am a boy, my height is 175 cm.
My salary is 9000 RMB.
- 类成员的作用域只在类的内部,外部无法直接访问
- 成员函数可以直接访问成员变量和调用成员函数
- 类的外部可以通过类变量访问 public 成员
- 类成员的作用域与访问级别没有关系
C++ 中用 struct 定义的类中所有成员默认为 public
#include <stdio.h>
int i = 1;
struct Test
{
private:
int i;
public:
int j;
int getI()
{
i = 3;
return i;
}
};
int main()
{
int i = 2;
Test test;
test.j = 4;
printf("i = %dn", i);
printf("::i = %dn", ::i);
// printf("test.i = %dn", test.i); // Error
printf("j = %dn", test.j);
printf("test.getI() = %dn", test.getI());
return 0;
}
输出:
i = 2
::i = 1
j = 4
test.getI() = 3
如果想访问类的成员变量或成员函数,都必须通过这个类的对象来进行,是否访问成功,需要看类成员变量或成员函数的访问级别。
对类而言是有作用域的,仅仅指的是类的成员变量和成员函数的作用域。
作用域与访问级别是不同的概念。
- 类通常可以分为使用方式和内部细节两部分
- 类的封装机制使得使用方式和内部细节相分离
- C++ 中通过定义类成员的访问级别实现封装机制
- public 成员可以在类的内部和外界访问和调用
- private 成员只能在类的内部被访问和调用
以上是脚本宝典为你收集整理的【C++】 15_类于封装的概念全部内容,希望文章能够帮你解决【C++】 15_类于封装的概念所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。