【发布时间】:2015-05-16 22:06:47
【问题描述】:
我尝试实现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;
}
我有一些错误:
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> *'
我不知道这些错误与什么有关。有趣的是,linked_ptr<T>(linked_ptr<T> const& other) 运行良好,但 linked_ptr<T>(linked_ptr<U> const& other) 却不行。
如何解决这些问题?我可以将两个复制构造函数合二为一吗?
附:当然,U 是T 的子代。
【问题讨论】:
-
通常,这样的错误会给出行号;如果您指出这些错误发生在代码中的何处,将会有很大帮助。
-
@Hurkyl,所有错误都发生在
linked_ptr<T>(linked_ptr<U> const& other)。
标签: c++ templates c++11 smart-pointers type-inference