您的位置:首页 > 编程语言 > C语言/C++

C++运算符重载:operator

2017-03-20 22:49 323 查看
运算符重载:operator(翻译:操作)
前置++

const Human& operator ++(){++i; (*p)++; return *this;} //返回引用,防止值返回时的内存开销

注意:++a;相当于a.operator++(),相当于调用函数,有返回值,也可以赋值

后置++
const Human operator ++(int) { Human old(*this); i++; (*p)++; return old;}  //因为临时作用域结束的时候,就会释放,所以如果返回引用是空,所以返回值。

加减+ / -
const Human operator +(const Human &r){return Human(i + r.geti(),*p+r.getp());}  //用const修饰形参,则需要r对象调用的函数要被const修饰,如:int
get () const;

赋值=
const Human &operator =(const Human &r) { if (this==&r) { return *this;} i = r.geti(); *p = r.getp();return *this; }  

赋值运算符重载不用开辟空间,而复制构造函数可以当做构造函数使用,要开辟空间。

转换类型运算符

operator int() { return i; } 
//调用时  Human man;int x=int(man);或者int x=(man);或者int x=man;

下标[]

    char &operator [](int index)
    {
        if (index >= 0 && index < length)
        {
            return size[index];
        }
        else
        {
            cout << "超出范围" << endl;
            return size[length];
        }
    }  

注意:
由于函数的参数即是数组的下标,因此该函数只能带一个参数,不可带多个参数。
由于下标运算符函数只限于本类的对象使用,因此不得将下标运算符函数重载为友元函数,且必须是非static类的成员函数。

<<:编译器判断<<左边是ostream的对象,就认为是输出;左边不是ostream的对象,就认为是位移操作符

普通函数:ostream& operator <<(ostream &out, const Human&man)
{
    out << man.age << endl;
    out << man.heither << endl;
    return out;//由于cout是另一个类ostream的对象,ostream类没有公共的构造函数,
    //因此函数无法调用该类的复制构造函数,必须按引用的方法接受ostream的对象,并按引用的方式返回ostream对象
}  

友元函数:friend ostream& operator <<(ostream &out, const Human&man)//因为该函数含有其他类的对象,所以这个函数就不能成为类Human的成员函数。加friend可以解决这个问题
    {
        out << man.age << endl;
        out << man.heither << endl;
        return out;
    }  

>>

friend istream& operator >>(istream &in, Human&man)//因为该函数含有其他类的对象,所以这个函数就不能成为类Human的成员函数。加friend可以解决这个问题
    {
        in >> man.age;
        in >> man.heither;
        return in;
    }  

C++的运算符大部分可以被重载,但是有一些却不能重载。如“.”,"::","*","? :","#".
“.”,"::","*"在c++中有特殊的意义,假如重载的话会引起一些麻烦。

"#"是预处理标志,而不是运算符

"? :"没有确定性,重载没有意义
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: