Is it possible to have an array with int values and int references?
Is there any other way to have an array arr
such that when you print arr[1]
it always prints the value of arr[0]
(without having to update arr[1]
when arr[0]
is modified) ?
No , but you may have such a desired array:
#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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.