C++:我很帅;但是我的缺点是:我帅的不明显。什么是幸福?幸福就是猫吃鱼,狗吃肉,奥特曼打小怪兽!令堂可是令尊表姐?我是胖人,不是粗人。
示例程序代码如下
#include ""
#include <>
class stack
{
private:
int *sp, top, max;
void inflate();
public:
stack(int size = 10)
{
sp = (int *)malloc(sizeof(int) * size);
max = size;
top = 0;
}
int pop();
void push(int value);
stack & operator=(stack & rightValue);
};
//栈的容量增倍
void stack::inflate()
{
int index, *tp;
tp = (int *)malloc(sizeof(int) * max * 2);
for(index = 0; index < top; index++)
{
tp[index] = sp[index];
}
max += max;
free(sp);
sp = tp;
}
//出栈
int stack::pop()
{
if(top <= 0)
throw 1;
return sp[--top];
}
//入栈
void stack::push(int value)
{
if(top == max)
inflate();
sp[top++] = value;
}
//赋值函数
stack & stack::operator=(stack & rightValue)
{
top = ;
max = ;
sp = (int *)malloc(sizeof(int) * max);
for(int index = 0; index < max; index++)
{
sp[index] = [index];
}
return *this;
}
void main()
{
stack x(100), y, z;
z = y = x;
}
这里要注意的是赋值函数的返回值是stack &,这是为了实现链式表达式,如z = y = x;。
这一点可见《高质量c/c++编程》(林锐)一书。
2.[]的重载
语法:值类型 operator[](一个形参) 函数体
示例程序如下:
#include ""
#include <>
#include <iostream>
using namespace std;
class Array
{
private:
int *a, len;
void inflate()
{
cout << "the array is inflating..." << endl
C 运算符重载实例 来自淘豆网www.taodocs.com转载请标明出处.