I have the following structure of a class for read-only variables (principle taken from here)
#include <iostream>
#include "test.h"
using namespace std;
int main(int argc, const char * argv[]) {
Test test;
cout << test.x << endl; // Should be 0.
test.f(test.x);
cout << test.x << endl; // Should be 10.
return 0;
}
with the class Test
#ifndef __CPP_Playground__test__
#define __CPP_Playground__test__
#include <iostream>
class Test {
private:
int x_;
public:
const int &x;
void f(int target);
Test() : x(x_) {}
};
#endif /* defined(__CPP_Playground__test__) */
and the appropriate cpp file
#include "test.h"
void Test::f(int target){
target = 10;
};
But it does not work. How can I fix this?