2016-05-13 53 views
0

是否有可能具有int值和int引用的數組?是否有可能具有int值和int引用的數組?

是否有任何其他的方式有一個陣列,使得arr打印時arr[1]它始終打印的arr[0]值(而不必在arr[0]被修改更新arr[1])?

+4

陣列必須包含相同類型的元素。 'int'和'int&'是不同的,所以沒有 – vu1p3n0x

+0

你打算做什麼? –

+9

這聽起來像[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。請詳細說明您的實際問題。 – TartanLlama

回答

0

No,但可能有這樣的所需的陣列:

#include <iostream> 
using namespace std; 

class CIntRef 
{ 
public: 
    CIntRef(const int & ref) : ref(ref) {} 
    operator const int &() { return ref; } 
    const int& operator=(const int &i) { 
     const_cast<int&>(ref) = i; 
     return ref; 
    } 
private: 
    const int & ref; 
}; 

int main() 
{ 
    int a = 2; 
    CIntRef arr[] = { a, a, 0, 1 }; 
    cout << arr[1] << endl; // <-- prints: 2 
    arr[0] = 3; 
    cout << arr[1] << endl; // <-- prints: 3 
    return 0; 
} 
相關問題