运算符重载
- 根据reciver的对象的类型决定调用哪个运算符重载函数。对于reciver对象不做类型转换。
class Integer
{
private:
int i;
public:
Integer(int i=0):i(i){};
void print(){
cout<<i<<endl;
}
const Integer operator+ (const Integer &that) const
{
return Integer(i + that.i);
};
};
int main()
{
Integer i=10;
Integer a=i+1000;
a.print();
return 0;
}
Integer x(10),y(200);
Interger z=x+y;
Interger z=x+3;
Interger z=3+y;
class Integer
{
private:
int i;
public:
Integer(int i=0):i(i){};
void print(){
cout<<i<<endl;
}
const Integer operator+ (const Integer &that) const
{
return Integer(i + that.i);
};
friend Integer operator+(const Integer &l,const Integer &r){
return Integer(l.i+r.i);
}
};
int main()
{
Integer i=10;
Integer a=1000+i;
a.print();
return 0;
}
Integer x=3+7;
- 技巧: (1) 单目运算符做成员函数 (2)= ,(), ->, ->* 必须是成员函数 (3)赋值应该是成员函数 (4) 其他的双目运算符非成员函数。
运算符重载-----原型
class Vector
{
private:
int * m_array;
int m_size;
public:
Vector(int size):m_size(size){m_array=new int[size];};
~Vector(){ delete m_array;};
int& operator [] (int index){
return m_array[index];
}
};
运算符重载-------赋值
class Fi{
public:
Fi(){};
};
class Fee
{
public:
Fee(int){};
Fee(const Fi&){};
~Fee(){};
};
int main(){
Fi fi;
Fee fum=fi;
fum=fi;
return 0;
}
T & T::operator=(const T & rhs){
if(this != &rhs){
}
return *this;
}
class A{
char * p;
A& operator=(const A& that)
{
delete p;
p=new [strlenstrlen(strlen(that.p))+1];
strcp(p,that.p);
return *this;
}