[英]I assigned a variable to the value of what is stored at a pointer's address, so why doesn't it change when the initial value does?
Basically, I just want to know why 'C' doesn't change when 'A' does.基本上,我只想知道为什么“A”发生变化时“C”不会改变。 I'm guessing that it's because of the hierarchy, but I wanted to confirm and get an explanation as to why...
我猜这是因为等级制度,但我想确认并解释为什么......
#include <iostream>
using namespace std;
class IntCell
{
public:
explicit IntCell( int initialValue = 0 )
{ storedValue = new int{ initialValue }; }
int read() const
{ return *storedValue; }
void write( int x )
{ *storedValue = x; }
private:
int *storedValue;
};
int main() {
IntCell a{ 2 };
IntCell* b = &a;
IntCell c;
int x = 10000;
int* y = &x;
cout << *y << endl;
c = *b;
a.write(4);
cout << a.read() << endl << c.read();
return 0;
}
I test your code and when you change "a", "c" change too.我测试你的代码,当你改变“a”时,“c”也会改变。 Also You need to implement a copy constructor and assignment operator.
您还需要实现一个复制构造函数和赋值运算符。
IntCell c; // you create a new instance with new memory address.
c = *b; // now this instance point to same memory as "a".
a.write(4); // so when you change "a", "c" change too.
In your case, the destructor is missing.在您的情况下,缺少析构函数。
~IntCell(){ cout<<"deleting...\n"; delete storedValue; }
You are using the implicitly-defined copy assignment.您正在使用隐式定义的复制分配。 That is why
c = *b;
这就是为什么
c = *b;
works.作品。 After the copy assignment,
IntCell c
and IntCell a
both have the member which points to the same location.复制分配后,
IntCell c
和IntCell a
都有指向同一位置的成员。 If a.write(4)
, c.read()
will get the same value 4
.如果
a.write(4)
, c.read()
将获得相同的值4
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.