【C++】15 类与封装的概念
文章目录
类的组合

类的封装
类通常分为两个部分
类的实现细节
类的使用方式
当使用类时,不需要关心实现细节
当创建类时,需要考虑内部实现细节

封装的基本概念
并不是类的每个属性都是对外公开的
而一些类的属性是对外公开的
必须在类的表示法中定义属性和行为的公开级别

C++中类的封装
成员变量:C++中用于表示类属性的变量
成员函数:C++中用于表示类行为的函数
C++中可以给成员变量和成员函数定义访问级别
public 成员变量和成员函数可以在类的内部和外界访问和调用
private 成员变量和成员函数只能在类的内部被访问和调用
#include <stdio.h>
struct Biology {
bool living;
};
struct Animal : Biology {
bool movable;
void findFood() { }
};
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'm girl,I'm %d years old.\n",age);
printf("My weight is %d kg.\n",weight);
}
};
struct Boy :Human
{
private:
int height;
int salart;
public:
int age;
int weight;
void print()
{
height = 175;
salart = 9000;
printf("I'm boy,my height is %d cm.\n",height);
printf("My salart is %d RMB.\n",salart);
}
private:
int a;
};
int main()
{
Girl g;
Boy b;
//printf("g.age = %d\n",g.age);
g.print();
b.age = 19;
b.weight = 120;
//b.height = 180;
b.print();
return 0;
}输出结果:
I'm girl,I'm 22 years old.
My weight is 48 kg.
I'm boy,my height is 175 cm.
My salart 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 = %d\n", i); // i = 2;
printf("::i = %d\n", ::i); // ::i = 1;访问默认命名空间里面的i变量,默认命名空间,就是全局作用域,
// printf("test.i = %d\n", test.i); // Error
printf("test.j = %d\n", test.j); // test.j = 4
printf("test.getI() = %d\n", test.getI()); // test.getI() = 3
return 0;
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论