提问人:xianshenglu 提问时间:1/17/2023 更新时间:1/17/2023 访问量:69
为什么复制构造函数更改了以前的对象指针成员
Why copy constructor changed previous object pointer member
问:
#include <iostream>
#include <string.h>
#include "Date.h"
#include "Employee.h"
using std::cout;
using std::endl;
using std::to_string;
class TestOps {
public:
int sex = 1;
string toString() {
return " sex:" + to_string(sex) ;
}
};
class Test {
public:
TestOps* testOps;
Test(const Test& t) :Test{} {
this->testOps = new TestOps{ *(t.testOps) };
};
Test() {
TestOps ops;
//this->testOps = new TestOps{}; // it will be ok with this way
this->testOps = &ops;
}
};
int main() {
// code not understand
Test t1;
cout <<"first testOps:" << t1.testOps->toString() << endl; // sex: 1
Test t2{ t1 };
cout << "first testOps:" << t1.testOps->toString() << endl; // sex: -858893460 ???? why?
cout << "second testOps:" << t2.testOps->toString() << endl; // sex: -858893460 ???? why?
return 0;
}
如您所见,为什么第一个日志符合预期,而后面的日志则不符合预期?
此外,地址与预期的地址不同。t1.testOps
t2.testOps
我做了一些研究,但没有找到答案。也许是因为我对 cpp 很陌生。
答: 暂无答案
评论
ops
在构造函数结束时死亡,对它的任何访问都会导致未定义的行为。Test
this->testOps = &ops;
tesOps
&
&