Skip to content

Instantly share code, notes, and snippets.

@qiaoxu123
Last active October 3, 2018 09:40
Show Gist options
  • Save qiaoxu123/c8ac44df7ce2b93bdc8a8bd7b8da5c5f to your computer and use it in GitHub Desktop.
Save qiaoxu123/c8ac44df7ce2b93bdc8a8bd7b8da5c5f to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
using namespace std;
class Test {
int i;
public:
Test(int i) {
cout << "Test(int i)" << endl;
this->i = i;
}
int value() {
return i;
}
Test() {
cout << "~Test()" << endl;
}
};
class Pointer {
Test* mp;
public:
Pointer(Test* p = NULL) {
mp = p;
}
Pointer(const Pointer& obj) {
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
}
Pointer& operator = (const Pointer& obj) {
if (this != &obj) {
delete mp;
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
}
return *this;
}
Test* operator -> () {
return mp;
}
Test& operator * () {
return *mp;
}
bool isNULL() {
return (mp == NULL);
}
~Pointer() {
delete mp;
}
};
int main() {
Pointer p1 = new Test(0);
cout << p1->value() << endl;
Pointer p2 = p1;
cout << p1.isNULL() << endl;
cout << p2.isNULL() << endl;
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment