笔记
用c的方式实现栈
用C++数据抽象的方式实现栈
#include<stdio.h>
struct
struct Stack
{
};
void StackInit(struct Stack* stack)
{
stack->head=NULL;
stack->size=0;
}
void StackPush(structStack*stack,const int data)
{
struct Link* node;
node=(struct Link*)malloc(sizeof(struct Link));
assert(node!=NULL);
node->data=data;
node->next=stack->head;
stack->head=node;
++stack->size;
}
int StackEmpty(struct Stack* stack)
{
return (stack->size==0);
}
int StackPop(struct Stack* stack,int* data)
{
if(StackEmpty(stack))
{
return 0;
}
struct Link* tmp=stack->head;
*data=stack->head->data;
stack->head=stack->head->next;
free(tmp);
--stack->size;
return 1;
}
void StackCleanup(struct Stack* stack)
{
struct Link* tmp;
while(stack->head)
{
tmp=stack->head;
stack->head=stack->head->next;
free(tmp);
}
stack->size=0;
}
int main(void)
{
struct Stack stack;
StackInit(&stack);
int i;
for(i=0;i<5;i++)
{
StackPush(&stack,i);
}
while(!StackEmpty(&stack))
{
StackPop(&stack,&i);
print("%d",i);
}
printf("\n");
return 0;
}
一,运算符重载
成员函数重载
非成员函数重载(友元)
运算符重载规则
重载各种运算符
体现了C++的可扩充性
运算符重载仅仅是语法上的方便,是一种函数调用的方式
运算符重载,本质上是函数重载
不要滥用重载
只有在涉及的代码更容易写,尤其是更容易读时才有必要重载
普通函数重载即可
重载格式:
函数类型 operator 运算符(参数表)
成员函数定义:
函数类型 类名::运算符(参数表)
{
函数体;
}
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
class Complex
{
public:
Complex(int real,int imag);
Complex();
~Complex();
Complex& Add(const Complex& other);
void Display() const;
Complex operator+(const Complex& other);
private:
int real_;
int imag_;
};
#endif//_COMPLEX_H_
#include"Complex.h"
#include<iostream>
using namesapce std;
Complex::Complex(int real,int imag):real_(real),imag_(imag)
{
}
Complex::Complex()
{
}
Complex::~Complex()
{
}
Complex& Complex::Add(const Complex& other)
{
real_+=other.real_;
imag_+=other.real_;
return *this;
}
Complex Complex::operator+(const Complex& other)
{
int r=real_+other.real_;
int i=imag_+other.imag_;
return *this;
}
void Complex::Display() const
{
cout<<real_<<"+"<<imag_<<"i"<<endl;
}
#include"Complex.h"
int main(void)
{
Complex c1(3,5);
Complex c2(4,6);
//c1.Add(c2);
//c1.Display();
Complex c3=c1+c2;
return 0;
}