开发者

How to bound 2 variables in C++ one with other so when one changes changes another?

开发者 https://www.devze.com 2023-01-13 11:02 出处:网络
How to bound 2 variables in C++ one with other so when one changes changes another? for example I created Int A and Int B bound one to another and than开发者_C百科 when I change A one using some func

How to bound 2 variables in C++ one with other so when one changes changes another?

for example I created Int A and Int B bound one to another and than开发者_C百科 when I change A one using some function another one will automatically change to new value of A.

I am intrested in version for C++ .net 4th version.


I don't know about the .Net version of C++, but you can use references in C++ to do what you want:

int  A = 0;
int& B = A;
...
A = 10;  // B == 10
B = 100; // A == 100


You can't do it with vanilla values, there needs to be indirection somewhere.

You could refer to one:

int a;
int& b = a;

a = 5;
assert(b == 5);

Point to one:

int a;
int* b = &a; // b points to a

a = 5;
assert(*b == 5);

Or create some utility for essentially wrapping the above.


How to bind 2 variables in C++ one with another so when one changes changes another?

You are looking for a concept called a reference, which is built on the concept called a pointer. The actual concept is that you want two Thingies pointing to a memory location.

for example I created Int A and Int B bound one to another and than when I change A one using some function another one will automatically change to new value of A.

You mean B will change to the new value of A, I take it.

int &B = A; creates the reference B that points to the location A refers to.

Another approach - not the best approach for a beginner - is:

int *A = new int;  //Get some heap memory for A to point to
int *B = A;        

That uses pointers.

I am interested in version for C++ .net 4th version.

Strictly speaking, C++ is an ISO standard; .NET doesn't have anything to do with C++. However, Microsoft has the C++/CLI language which is sorta C++, but really isn't.


You give up on the idea of doing so with fundamental types and make A an observable.

0

精彩评论

暂无评论...
验证码 换一张
取 消