下面是类的定义
Test
:
class Test {
private:
static int count;
int x;
public:
Test(int _x = 0): x(_x) {
count++;
}
~Test() {
count--;
}
int getX() {return x;}
int operator+= (int what) {
return x += what;
}
friend ostream& operator<<(ostream& o, Test& t);
static int getCount() {return count;}
};
ostream& operator<<(ostream& o, Test& t) {
o << t.x;
return o;
}
int Test::count = 0;
类的定义
my_ptr
:
template <typename T>
class my_ptr{
T* ptr;
static T* t;
public:
my_ptr(T* _ptr = nullptr) :ptr(_ptr) {cout << "my_ptr constructed." << endl;}
~my_ptr(){
cout << "my_ptr destructed." << endl;
delete ptr;
}
};
以下是我感到困惑的内容:
my_ptr<Test> ptr3, ptr4
cout << *ptr3 << endl;
cout << *ptr4 << endl;
*ptr3 = 8234356;
cout << ptr4->getX() << endl;
我想为
my_ptr
和 *
实现类 ->
的操作重载,以使类 my_ptr
更像一个 unique_ptr。当使用 *
或 ->
访问 nullptr 时,我应该返回警告文本和静态预设指针。
但是我想像第 4 行那样更改
Test::x
的值,但是当我尝试像下面那样重载 *
运算符时,我注意到由于 ptr3.ptr
是一个 nullptr,第 4 行将简单地更改 的值ptr3.t
但不是ptr3.ptr
.
friend T& operator*(my_ptr& mp){
if (mp.ptr != nullptr) return *mp.ptr;
return *t;
cout << "Do not attempt to read a nullptrptr!" << endl;
}
我该如何解决这个问题?