【问题标题】:Is it possible to have an array with int values and int references?是否可以有一个包含 int 值和 int 引用的数组?
【发布时间】:2016-09-09 19:52:08
【问题描述】:

是否可以有一个包含 int 值和 int 引用的数组?

有没有其他方法可以拥有一个数组arr,这样当你打印arr[1]时,它总是打印arr[0]的值(当arr[0]被修改时,不必更新arr[1])?

【问题讨论】:

  • 数组必须包含相同类型的元素。 intint& 不同,所以没有
  • 你打算做什么?
  • 这听起来像是XY problem。请详细说明您的实际问题。
  • 你不能有一个 any 引用的数组。你可以有一个引用包装数组,它们是变相的指针。
  • boost::variant 会这样做。

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


【解决方案1】:

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;
}

【讨论】:

    猜你喜欢
    • 2012-08-14
    • 1970-01-01
    • 2013-01-21
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2020-06-08
    相关资源
    最近更新 更多