面向对象和面向过程_实例(数组模拟实现栈)代码对比面向过程和面向对象

直接看代码:

67b11de63876d4415b5f9f70fa330dcd.png

相同的运行效果:

/*Enter some integers, ending with 02 6 9 12 3 0Numbers in reverse order3 12 9 6 2*/

我们知道,我们构建程序,特别是大型程序,如同构建一幢建筑物,可以使用构建块,程序的构建块可以是函数,也可以是类对象。如上,相同的问题,可以用面向过程的函数块来构建,也可以用面向对象的对象块来构建,对比一下,对象块的封装性与独立性更强,特别是面对大型程序,面对更复杂的问题,对象之间的继承、组合、依赖、联合、包含等关系可以通过不同的设计模式去实现。

附代码1

#include #include #define RogueValue -9999#define MaxStack 10typedef struct stack{int top;int ST[MaxStack];}StackType, *Stack;Stack initStack();int empty(Stack);void push(Stack, int);int pop(Stack);int top(Stack);Stack initStack() {Stack sp = (Stack) malloc(sizeof(StackType));sp -> top = -1;return sp;}int empty(Stack S) {return (S -> top == -1);}void push(Stack S, int n) {if (S -> top == MaxStack - 1) {printf("Stack Overflow");exit(1);}++(S -> top);S -> ST[S -> top]= n;}int pop(Stack S) {if (empty(S)) return RogueValue;int hold = S -> ST[S -> top];--(S -> top);return hold;}int top(Stack S) {if (empty(S)) return RogueValue;int hold = S -> ST[S -> top];return hold;}int main() {int n;Stack S = initStack();printf("Enter some integers, ending with 0");scanf("%d", &n);while (n != 0) {push(S, n);scanf("%d", &n);}printf("%d",top(S));printf("Numbers in reverse order");while (!empty(S))printf("%d ", pop(S));system("pause");printf("");}

附代码2

#include #include #define RogueValue -9999#define MaxStack 10class Stack{int top;int ST[MaxStack];public:Stack();int empty();void push(int);int pop();int getTop();};Stack::Stack() {top = -1;}int Stack::empty() {return (top == -1);}void Stack::push(int n) {if (top == MaxStack - 1) {printf("Stack Overflow");exit(1);}++(top);ST[top]= n;}int Stack::pop() {if (empty()) return RogueValue;int hold = ST[top];--(top);return hold;}int Stack::getTop() {if (empty()) return RogueValue;int hold = ST[top];return hold;}int main() {int n;Stack s;printf("Enter some integers, ending with 0");scanf("%d", &n);while (n != 0) {s.push(n);scanf("%d", &n);}printf("Numbers in reverse order");while (!s.empty())printf("%d ", s.pop());system("pause");printf("");} /*Enter some integers, ending with 02 6 9 12 3 0Numbers in reverse order3 12 9 6 2*/

-End-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值