1. 程式人生 > 其它 >【C++の相關概念】重溫字首++與字尾++

【C++の相關概念】重溫字首++與字尾++

技術標籤:C++の相關概念

字首++與字尾++的本指區別是什麼?

int i = 0, n = 0;

int test = ++i;
//此時,test等於1,i也等於1
test = n++;
//此時,test等於0,n等於1
因此,要說本質區別就是字首加加返回自增後的自己,而後綴加加是返回自增前的值

字首++與字尾++的類成員函式過載是怎樣的?

Complex& operator++()//字首++過載 返回的是引用
Complex operator++(int)// 字尾++過載寫法 (int) 區分字首的必須寫成int 返回是右值物件
字首++返回引用,字尾++返回右值!!!
所以沒有int i=1; i++++;

這種寫法
也沒有int i=1; ++i++;這種寫法
但是可以int i=1; i++++;結果為i=3

假設it為指標*(it++)和*(++it)和*it++和*++it和(*it)++和++(*it)的區別是什麼?

  • *it++ 和 *(it++) 的結果是一樣的
    先執行*it返回結果,再將it++
  • *++it 和 *(++it) 的結果是一樣的
    先執行it++,再將*it返回結果
    簡而言之,加不加括號沒有改變結果…
  • (*it)++顧名思義就是先取*it的值,然後再把解地址處的值進行++
    (*it)++顧名思義就是先把解地址處的值進行++,然後再取*it的值

以下是測試程式碼以及結果:

void
test(int* it, int situation) { if (situation == 1) { cout << "*it = " << *it << endl; int tmp = *(it++); cout << "tmp = *(it++) = " << tmp << endl; cout << "now *it = " << *it << endl; } else if (situation ==
2) { cout << "*it = " << *it << endl; int tmp = *(++it); cout << "tmp = *(++it) = " << tmp << endl; cout << "now *it = " << *it << endl; } else if (situation == 3) { cout << "*it = " << *it << endl; int tmp = *it++; cout << "tmp = *it++ = " << tmp << endl; cout << "now *it = " << *it << endl; } else if (situation == 4) { cout << "*it = " << *it << endl; int tmp = *++it; cout << "tmp = *++it = " << tmp << endl; cout << "now *it = " << *it << endl; } else if (situation == 5) { cout << "*it = " << *it << endl; int tmp = (*it)++; cout << "tmp = (*it)++ =" << tmp << endl; cout << "now *it = " << *it << endl; } else if (situation == 6) { cout << "*it = " << *it << endl; int tmp = ++(*it); cout << "tmp = ++(*it) = " << tmp << endl; cout << "now *it = " << *it << endl; } else { cout << "error;" << endl; } } int main() { int a[10] = { 1,2,3,4,5,6,7,8,9 }; test(a + 3, 1); cout << endl; test(a + 3, 2); cout << endl; test(a + 3, 3); cout << endl; test(a + 3, 4); cout << endl; test(a + 3, 5); cout << endl; test(a + 3, 6); cout << endl; return 0; }

在這裡插入圖片描述