Den*_*nis 4 c++ templates type-inference smart-pointers c++11
我试着实施linked_ptr.这是一项研究任务.这是我的代码的一部分:
template <class T>
class linked_ptr
{
public:
//***************
linked_ptr<T>(linked_ptr<T> const& other)
{
p = other.p;
left_ptr = &other;
right_ptr = other.right_ptr;
if (other.right_ptr != nullptr)
{
(other.right_ptr)->left_ptr = this;
}
other.right_ptr = this;
}
template <class U>
linked_ptr<T>(linked_ptr<U> const& other)
{
p = other.p;
left_ptr = &other;
right_ptr = other.right_ptr;
if (other.right_ptr != nullptr)
{
(other.right_ptr)->left_ptr = this;
}
other.right_ptr = this;
}
private:
T *p;
mutable linked_ptr const* left_ptr;
mutable linked_ptr const* right_ptr;
};
class A
{
public:
int a = 0;
A(int aa)
{
a = aa;
}
};
class B : public A
{
public:
B(int bb)
{
a = bb;
}
};
int main()
{
linked_ptr<B> a(new B(5));
linked_ptr<A> b(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我有一些错误:
cannot access private member declared in class 'smart_ptr::linked_ptr<B>'
cannot access private member declared in class 'smart_ptr::linked_ptr<B>'
cannot access private member declared in class 'smart_ptr::linked_ptr<B>'
cannot access private member declared in class 'smart_ptr::linked_ptr<B>'
cannot access private member declared in class 'smart_ptr::linked_ptr<B>'
cannot access private member declared in class 'smart_ptr::linked_ptr<B>'
ptr::linked_ptr<B> *' to 'const smart_ptr::linked_ptr<A> *'
ptr::linked_ptr<B> *' to 'const smart_ptr::linked_ptr<A> *'
linked_ptr<A> *const ' to 'const smart_ptr::linked_ptr<B> *'
linked_ptr<A> *const ' to 'const smart_ptr::linked_ptr<B> *'
Run Code Online (Sandbox Code Playgroud)
我不知道这些错误有什么关系.有趣的是,linked_ptr<T>(linked_ptr<T> const& other)效果很好,但linked_ptr<T>(linked_ptr<U> const& other)没有.
我该如何解决这些问题?我可以将两个复制构造函数合二为一吗?
PS当然,U是一个孩子T.
当T与U有不同的类型,然后linked_ptr<T>和linked_ptr<U>有不同的类型.这意味着他们无法看到对方的私人成员.
你需要结交其他linked_ptr朋友:
template <class T>
class linked_ptr {
// The rest...
template<class U>
friend class linked_ptr;
};
Run Code Online (Sandbox Code Playgroud)