C 에서 사용자 정의 클래스 2 가지 자체 연산 코드 의 실현 과 차이

2511 단어 kezunlin.me
본문 은 개인 블 로그 에 처음 게재 되 었 다.https://kezunlin.me/post/caef83a3/, 최신 내용 을 읽 는 것 을 환영 합 니 다!
cpp i vs i for user defined class
Guide
code
#include 
#include 
#include 
#include 
#include 
using namespace std;

class Integer
{
public:
    Integer(int value): v(value)
    {
        cout << "default constructor" << endl;
    }
    Integer(const Integer &other)
    {
        cout << "copy constructor" << endl;
        v = other.v;
    }
    Integer &operator=(const Integer &other)
    {
        cout << "copy assignment" << endl;
        v = other.v;
        return *this;
    }

    //   i  first  1,then return new value
    Integer &operator  ()
    {
        cout << "Integer::operator  ()" << endl;
        v  ;
        return *this;
    }

    // i    first save old value,then  1,last return old value
    Integer operator  (int)
    {
        cout << "Integer::operator  (int)" << endl;
        Integer old = *this;
        v  ;
        return old;
    }

    void output()
    {
        cout << "value " << v << endl;
    }
private:
    int v;
};

void test_case()
{
    Integer obj(10);
    Integer obj2 = obj;
    Integer obj3(0);
    obj3 = obj;
    cout << "--------------" << endl;
    cout << "  i" << endl;
      obj;
    obj.output();
    cout << "i  " << endl;
    obj  ;
    obj.output();
}

int main()
{
    test_case();
    return 0;
}

output
    default constructor
    copy constructor
    default constructor
    copy assignment
    --------------
      i
    Integer::operator  ()
    value 11
    i  
    Integer::operator  (int)
    copy constructor
    value 12

Reference
  • iplusplus_plusplusi

  • History
  • 2019/11/08: created.

  • Copyright
  • Post author: kezunlin
  • Post link: https://kezunlin.me/post/caef83a3/
  • Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

  • Copyright
  • Post author: kezunlin
  • Post link: https://kezunlin.me/post/caef83a3/
  • Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.
  • 좋은 웹페이지 즐겨찾기