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;
    }
  • 相关阅读:
    Promise
    replace
    mongogogog
    sh back mongo
    mongodb 备份 还原 导出 导入
    mongo virtual
    openssl
    isMobile
    google api autocomplete
    npm
  • 原文地址:https://www.cnblogs.com/cs1003/p/2834213.html
Copyright © 2011-2022 走看看