[已解决]
#include "std_lib_facilities.h"
template <class T>
class counted_ptr{
private:
T* pointer;
int* count;
public:
counted_ptr(T* p = 0, int* c = new int(1)) : pointer(p), count(c) {} // default constructor
explicit counted_ptr(const counted_ptr& p) : pointer(p.pointer), count(p.count) { ++*count; } // copy constructor
~counted_ptr() { --*count; delete pointer; }
counted_ptr& operator=(const counted_ptr& p)
{
pointer = p.pointer;
count = p.count;
++*count;
return *this;
}
T* operator->() const{ return pointer; }
T& operator*() const { return *pointer; }
int Get_count() const { return *count; }
};
int main()
{
counted_ptr<double> one;
counted_ptr<double>two(one);
int a = one.Get_count();
cout << a << endl;
}
当我尝试执行以下操作时:
one->pointer = new double(5);
然后我收到一个编译器错误,说“请求访问非类类型double的'*(&amp;one) -> counted_ptr :: operator-&gt; with T = double'中的成员'pointer'。”
我考虑制作一个函数来解决这个问题,虽然我可以创建一个函数来分配T类型的数组,但我想不出一种分配实际对象的方法。感谢任何帮助。
counted_ptr
提供一个新的指针以保存时,您是否希望其他的counted_ptr
指向新指针还是旧指针? - outis