是否可以使用int值和int引用的数组?

时间:2016-05-13 14:43:49

标签: c++ pointers reference pass-by-reference pass-by-value

是否可以使用int值和int引用的数组?

是否有其他方法可以使用数组arr,这样当您打印arr[1]时,它始终会打印arr[0]的值(当{时无需更新arr[1] {1}}已修改)?

1 个答案:

答案 0 :(得分: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;
}