c++/oop---可变长整形数组/流插入,流提取运算符的重载
可变整型数组
查看代码
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
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<<t[0]<<' '<<t[1]<<' '<<t[2]<<endl;
Array t2=t;
cout<<t2[0]<<' '<<t2[1]<<' '<<t2[2]<<endl;
return 0;
}
流插入,流提取运算符的重载
1.流插入运算符<<
ostream & operator <<(ostream &,自定义类 &形参对象)
istream & operator >>(istream &,自定义类 &形参对象)
只能声明为友元函数
查看代码
#include <iostream>
#include <cstring>
#include <cstdlib>
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<l&&isdigit(s[x]);x++)r=r*10+s[x]-'0';
for(x++;x<l&&isdigit(s[x]);x++)i=i*10+s[x]-'0';
}
friend ostream & operator << (ostream &,Complex & a);
friend istream & operator >> (istream &,Complex & a);
};
ostream & operator << (ostream & output,Complex & a){
output<<a.r<<'+'<<a.i<<'i'<<endl;
return output;//continuous output
}
istream & operator >> (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<<endl;
cout<<a<<'\n'<<a<<endl;
cin>>a;
cout<<a<<endl;
return 0;
}
实现原理:
(cout.operator<<("STARWAR")).operator<<(5)
cout.operator<<("STARWAR") 这是个 ostream 类型的引用,其实就是 cout 的引用