OOP是Object Oriented Program
//non-OO Solution #include <stdio.h> #define STACK_SIZE 00 struct Stack{ int top; int buffer[STACK_SIZE]; }; //push和Stack是相关的,但是不是显式相关 bool push(Stack &s, int i){ if(s.top == STACK_SIZE - 1) { printf("Stack is overflow.\n"); return false; }else{ s.top++; s.buffer[s.top] = i; return true; } } bool pop(Stack &s, int &i){ if (s.top == -1){ printf("Stack is empty.\n"); return false; }else{ i = s.buffer[s.top]; s.top--; return true; } } void main(){ Stack st1, st2; st1.top = -1;//安全隐患 st2.top = -1;//安全隐患 int x; push(st1,12); pop(st1,x); //可以直接操控其中的数据 st1.buffer[2] = -1;//违背ADT st2.buffer[2]++; //违背ADT }
#include <iostream.h> #define STACK_SIZE 100 class Stack { private: int top; int buffer[STACK_SIZE]; public: Stack(){ top = -1; }//定义的构造方法 bool push(int i); bool pop(int& i); }; bool Stack::push(int i);{ if (top == STACK_SIZE-1) { cout << "Stack is overflow.\n"; return false; }else{ top++; buffer[top] = i; return true; } } bool Stack::pop(int& i){ if (top == -1) { cout << "Stack is empty.\n"; return false; }else { i = buffer[top]; top--; return true; } } void main() { Stack st1,st2; int x; st1.push(12); st1.pop(x); //st1.buffer[2] = -1无法操作 //cfront用来检查 }
struct Stack{ int top; int buffer[STACK_SIZE]; }; //this是指向自己的指针 //对象的函数至少都持有一个this bool push(Stack *const this,int i);{ if (top == STACK_SIZE-1) { cout << "Stack is overflow.\n"; return false; }else{ top++; buffer[top] = i; return true; } } bool pop(Stack *const this,int& i){ if (top == -1) { cout << "Stack is empty.\n"; return false; }else { i = buffer[top]; top--; return true; } } void main(){ Stack st1, st2; st1.top = -1; st2.top = -1; int x; push(st1,12); pop(st1,x); }
具体到markdown文件中
int i; if(typeid(i) == typeid(int) ) cout << "i is int" << endl ; else cout << "i is not int" << endl ;
template<class T> void func(T t ){ cout << "i is not int" << endl ; } template<> void func<int>(int i){//特化 cout << "i is int" << endl ; } int i; func(i)