0
朋友函數析構指針,我仍然可以用指針訪問類的函數。私有析構函數的朋友函數
#include <iostream>
using namespace std;
// A class with private destuctor
class Test
{
private:
~Test()
{
cout<<"Inside destructor"<<endl;
}
friend void destructTest(Test*);
public:
void display()
{
cout<<"I am display func:"<<this<<endl;
}
};
void destructTest(Test* ptr)
{
cout<<"In here:"<<ptr<<endl;
delete ptr;
ptr = NULL;
}
int main()
{
Test *ptr;
ptr = new Test;
destructTest (ptr);
ptr->display();// this gets called properly!
return 0;
}
指針引用是如何保持的?我甚至試着將這段代碼的某些部分(= new Test())移到另一個函數中,以查看它是否與本地引用相關,但引用保持到程序結束!
只有當我把PTR = NULL,則destructTest通話後,它仍然會調用顯示功能,但給爲0
它被稱爲*未定義的行爲*。它可能似乎有效,但你不能依賴它。與朋友功能完全無關。 – juanchopanza
另外,'destructTest()'中的'ptr = NULL'語句沒有意義,因爲它只修改'ptr'的本地副本,並且不會返回'main()'中的'ptr',仍然保留舊值,而不管對象已被刪除...... – twalberg