zoukankan      html  css  js  c++  java
  • 自增自减运算符的重载(强制类型转换运算符重载)

    前置运算符重载为一元运算符,后置运算符重载为二元运算符。

    Operator int() { return n; }

    int作为一个强制类型转换运算符被重载,

    Demo s;

    (int)s;       //等效于s.int();

    强制类型转换运算符重载时,

    • 不能写返回值类型
    • 实际上其返回值类型----强制类型转换运算符代表的类型
    • 只能作为成员函数,不能作为友元函数或普通函数
    • 转换构造函数和类型转换运算符有一个共同的功能:当需要的时候,编译系统会自动调用这些函数,建立一个无名的临时对象(或临时变量)。

    运算符重载的注意事项

    • C++不允许定义新的运算符
    • 重载后运算符的含义应该符合日常习惯
    • 运算符重载不改变运算符的优先级
    • 以下运算符不能被重载:“.”,“.*”,“::”,“?:”,sizeof
    • 重载运算符(),[],->或者赋值运算符=时,重载函数必须声明为类的成员函数。
    #include <iostream>
    
    using namespace std;
    
    class Ctype
    {
    private:
        int n;
    public:
        Ctype(int m) :n(m) {};
        Ctype  operator ++(int);
        Ctype  operator ++();
        operator int();
    };
    Ctype  Ctype::operator++(int)
    {
        Ctype tmp(*this);
        n++;
        return (tmp);
    }
    Ctype  Ctype::operator++()
    {
        n++;
        return (*this);
    }
    Ctype::operator int()
    {
        return n;
    }
    int main()
    {
        Ctype c(6);
        cout << c++ << endl;
        cout << c << endl;
        cout << ++c << endl;
        return 0;
    }

     参考链接:

    https://www.coursera.org/learn/cpp-chengxu-sheji

  • 相关阅读:
    MySQL动态添删改列字段
    关于javascript在子页面中函数无法调试问题的解决
    <T> T[] toArray(T[] a);
    MERGE INTO
    eclipse不能新建server
    关于tomcat7下websocket不能使用
    myeclipse启动tomcat报错cannot find a free socket for debugger
    checkbox提交多组数据到action
    Struts2 Action中的方法命名不要以get开头
    浅谈C#中的接口和抽象类
  • 原文地址:https://www.cnblogs.com/helloforworld/p/5655272.html
Copyright © 2011-2022 走看看