gpt4 book ai didi

c++ - 为什么类的方法不能访问我类的某些字段?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:57 27 4
gpt4 key购买 nike

我尝试执行 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)没有。

我该如何解决这些问题?我可以将两个复制构造函数合并为一个吗?

附言当然,UT 的 child .

最佳答案

TU是不同的类型,那么 linked_ptr<T>linked_ptr<U>是不同的类型。这意味着他们看不到对方的私有(private)成员。

您需要制作其他linked_ptr friend 们:

template <class T>
class linked_ptr {
// The rest...

template<class U>
friend class linked_ptr;
};

关于c++ - 为什么类的方法不能访问我类的某些字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29048941/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com