zoukankan      html  css  js  c++  java
  • 关于运算符 前置 ++ 和后置++ ()

    1: 普通函数时

          前置++:参数 是一个非只读的引用类型,返回类型是一个非只读类型的引用。而且必须是先运算后取值

          后置++: 参数是一个非只读的引用类型和一个int型(int型没什么作用,用来区分前置和后置)。返回值是一个普通类 ,先取值后运算(可以用一个无名对象)

    #include<iostream>
    #include<stdio.h>
    #include<string>
    using namespace std;
    class A{
        int n;
        public:
        A(int n):n(n){}
        int get();
        friend A& operator++(A &a);
        friend A operator++(A &a,int b);
    };
    A& operator++(A & a)
    {
         a.n++;
         return  a;
    }
    A   operator++(A&a,int b)
    {
        return   A(a.n++);
    }
    int A::get()
    {
        return n;
    }
    int main()
    {
         A a=5;
         (++(++a))++;
         cout<<a.get()<<endl;
         A b=a++;
         cout<<b.get()<<" "<<a.get()<<endl;
         system("pause");
         return 0;
    }

     2: 函数成员时:

          

         前置++:无参数(有一个隐含的this指针,指向当前对象,)返回类型是一个非只读类型的引用。而且必须是先运算后取值

          后置++: 一个int型(int型没什么作用,用来区分前置和后置)还有一个(隐含的this类型,指向当前对象)。返回值是一个普通类 ,先取值后运算(可以用一个无名对象)

         

    #include<iostream>
    #include<stdio.h>
    #include<string>
    using namespace std;
    class A{
        int n;
        public:
        A(int n):n(n){}
        int get();
        A& operator++();
        A operator++(int b);
    };
    A& A::operator++()
    {
         n++;
         return  *this;
    }
    A   A::operator++(int b)
    {
        return   A(n++);
    }
    int A::get()
    {
        return n;
    }
    int main()
    {
         A a=5;
         (++(++a))++;
         cout<<a.get()<<endl;
         A b=a++;
         cout<<b.get()<<" "<<a.get()<<endl;
         system("pause");
         return 0;
    }

      3:利用友元来写:

       

    #include<iostream>
    #include<stdio.h>
    #include<string>
    using namespace std;
    class A{
        int n;
        public:
        A(int n):n(n){}
        friend int get(A a);
        A& operator++();
        A operator++(int b);
    };
    A& A::operator++()
    {
         n++;
         return  *this;
    }
    A   A::operator++(int b)
    {
        return   A(n++);
    }
    int get(A a)
    {
        return a.n;
    }
    int main()
    {
         A a=5;
         (++(++a))++;
         cout<<get(a)<<endl;
         A b=a++;
         cout<<get(b)<<" "<<get(a)<<endl;
         system("pause");
         return 0;
    }
  • 相关阅读:
    set
    皮肤病药物
    C 批量保存图片进 mysql 利用MYSQL_BIND插入longblob
    eclipse行号显示
    dynamic_cast使用
    list添加删除操作
    VS2008 对齐代码
    c++ mysql二进制存取,blob存取
    Select Window关键字——模拟打开了多个页面窗口时,在不同的窗口之间,进行窗口切换
    Click Image关键字——模拟单击某一个图片 其余:Click Button / Click Link
  • 原文地址:https://www.cnblogs.com/cs1003/p/2834213.html
Copyright © 2011-2022 走看看