c++/oop---可变长整形数组/流插入,流提取运算符的重载
可变整型数组
查看代码
#include
#include
#include
#include
#include
#include
using namespace std;
class Array{
private:
int size;//number of element
int *ptr;//postion
public:
Array (int s=0);
Array (const Array & a);
~Array();
void push_back(int v);
Array & operator =(const Array & a);
int length(){ return size; }
int & operator [](int i){return ptr[i];}
};
Array::Array(int s):size(s){
if(s==0)ptr=NULL;
else ptr = new int [s];
}
Array::~Array(){
if(ptr)delete [] ptr;
}
Array::Array(const Array & a){
if(!a.ptr){
ptr=NULL;size=0;
return;
}
ptr=new int [a.size];
memcpy(ptr,a.ptr,sizeof(int)*a.size);
size=a.size;
}
Array & Array::operator =(const Array & a){
if(ptr==a.ptr)return *this;//a=a;
if(ptr)delete [] ptr;
if(a.ptr==NULL){
ptr=NULL;size=0;
return *this;
}
ptr=new int [a.size];
memcpy(ptr,a.ptr,sizeof(int)*a.size);
size=a.size;
return *this;
}
void Array::push_back(int v){
if(!ptr){
ptr = new int [1];
}
else {
int * tmp =new int [size+1];
memcpy(tmp,ptr,sizeof(int)*size);
delete [] ptr;
ptr=tmp;
}
ptr[size++]=v;
}
int main(){
Array t;
t.push_back(1);
t.push_back(2);
t.push_back(3);
cout<
流插入,流提取运算符的重载
1.流插入运算符<<
ostream & operator <<(ostream &,自定义类 &形参对象)
istream & operator >>(istream &,自定义类 &形参对象)
只能声明为友元函数
查看代码
#include
#include
#include
using namespace std;
class Complex {
private:
double r,i;
public:
void Print() {
cout << r << "+" << i << "i" << endl;
}
Complex () {}
Complex (const char *s){
r=0,i=0;
int l = strlen(s),x;
for(x=0;x> (istream &,Complex & a);
};
ostream & operator << (ostream & output,Complex & a){
output<> (istream & input,Complex & a){
input>>a.r>>a.i;
return input;
}
int main() {
Complex a;
a = "3+4i"; a.Print();
a = "5+6i"; a.Print();
cout<>a;
cout<