标签:uri pos logs namespace value 自定义类 code efi history
本文首发于个人博客https://kezunlin.me/post/caef83a3/,欢迎阅读最新内容!
cpp i++ vs ++i for user defined class
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
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
标签:uri pos logs namespace value 自定义类 code efi history
原文地址:https://www.cnblogs.com/kezunlin/p/12125708.html