以下结果非常有趣,我很难理解它们。基本上我有它有一个int类:C++中指针的奇怪行为
class TestClass{
public:
int test;
TestClass() { test = 0; };
TestClass(int _test) { test = _test; };
~TestClass() { /*do nothing*/ };
};
它接受的TestClass的指针测试功能
void testFunction1(TestClass *ref){
delete ref;
TestClass *locTest = new TestClass();
ref = locTest;
ref->test = 2;
cout << "test in testFunction1: " << ref->test << endl;
}
这是我在做什么主:
int main(int argc, _TCHAR* argv[])
{
TestClass *testObj = new TestClass(1);
cout << "test before: " << testObj->test << endl;
testFunction1(testObj);
cout << "test after: " << testObj->test << endl;
return 0;
}
我期待输出为:
test before: 1
test in testFunction1: 2
test after: 1
但我得到以下输出:
test before: 1
test in testFunction1: 2
test after: 2
有人可以解释这一点。有趣的是,改变testFunction1到:
void testFunction1(TestClass *ref){
//delete ref;
TestClass *locTest = new TestClass();
ref = locTest;
ref->test = 2;
cout << "test in testFunction1: " << ref->test << endl;
}
即我不把它指向新的位置之前删除裁判,我得到下面的输出:
test before: 1
test in testFunction1: 2
test after: 1
我会很感激,如果有人可以给我解释一下这种奇怪的行为。谢谢。
没有更改主 – umair