Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
Clark Lin
StudyCpp
Commits
941ec765
Commit
941ec765
authored
Nov 22, 2022
by
Administrator
Browse files
add encapsulation and interface
parent
aecbb540
Changes
2
Hide whitespace changes
Inline
Side-by-side
02.OOP/Encapsulation.cpp
0 → 100644
View file @
941ec765
#include <iostream>
using
namespace
std
;
class
Adder
{
public:
// 构造函数
Adder
(
int
i
=
0
)
{
total
=
i
;
}
// 数据封装是一种把数据和操作数据的函数捆绑在一起的机制,
// 外部调用累加操作时,只需要提供累加的数量,具体的实现逻辑封装在类的公有函数中
// 对外的接口
void
addNum
(
int
number
)
{
total
+=
number
;
}
// 数据封装是一种把数据和操作数据的函数捆绑在一起的机制,
// 外部调用取累加值,不需要了解实际逻辑,具体的实现逻辑封装在类的公有函数中
// 对外的接口
int
getTotal
()
{
return
total
;
};
private:
// 对外隐藏的数据
// 数据抽象是一种仅向用户暴露接口而把具体的实现细节隐藏起来的机制。
// 对于数量的和,定义为私有成员,使它不直接对外可见
int
total
;
};
int
main
()
{
Adder
a
;
a
.
addNum
(
10
);
a
.
addNum
(
20
);
a
.
addNum
(
30
);
cout
<<
"Total "
<<
a
.
getTotal
()
<<
endl
;
return
0
;
}
\ No newline at end of file
02.OOP/Interface.cpp
0 → 100644
View file @
941ec765
#include <iostream>
using
namespace
std
;
// 基类
// 如果类中至少有一个函数被声明为纯虚函数,则这个类就是抽象类。
// 设计抽象类(通常称为 ABC)的目的,是为了给其他类提供一个可以继承的适当的基类。
// 抽象类不能被用于实例化对象,它只能作为接口使用。
// 如果试图实例化一个抽象类的对象,会导致编译错误。
class
Shape
{
public:
// 提供接口框架的纯虚函数
virtual
int
getArea
()
=
0
;
void
setWidth
(
int
w
)
{
width
=
w
;
}
void
setHeight
(
int
h
)
{
height
=
h
;
}
protected:
int
width
;
int
height
;
};
// 派生类 矩形
class
Rectangle
:
public
Shape
{
public:
// 基类的纯虚函数,在派生类中实现了具体逻辑
int
getArea
()
{
return
(
width
*
height
);
}
};
// 派生类 三角形
class
Triangle
:
public
Shape
{
public:
// 基类的纯虚函数,在派生类中实现了具体逻辑
int
getArea
()
{
return
(
width
*
height
)
/
2
;
}
};
int
main
(
void
)
{
Rectangle
Rect
;
Triangle
Tri
;
Rect
.
setWidth
(
5
);
Rect
.
setHeight
(
7
);
// 输出对象的面积
cout
<<
"Total Rectangle area: "
<<
Rect
.
getArea
()
<<
endl
;
Tri
.
setWidth
(
5
);
Tri
.
setHeight
(
7
);
// 输出对象的面积
cout
<<
"Total Triangle area: "
<<
Tri
.
getArea
()
<<
endl
;
return
0
;
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment