这是我的班级声明:
template <class T>
class Sptr {
template<typename U> friend class Sptr;
template <typename T1, typename T2>
friend bool operator==(const Sptr<T1> &a, const Sptr<T2> &b);
template <typename U>
friend Sptr<T> static_pointer_cast(const Sptr<U> &sp);
private:
RC* ref; //reference counter
T* obj;//pointer to current obj
std::function<void()> destroyData;
bool ok_;
public:
Sptr();
~Sptr();
template <typename U>
Sptr(U *);
Sptr(const Sptr &);
template <typename U>
Sptr(const Sptr<U> &);
template <typename U>
Sptr<T> &operator=(const Sptr<U> &);
Sptr<T> &operator=(const Sptr<T> &);
void reset();
T* operator->() const
{return obj;};
T& operator*() const
{return *obj;};
T* get() const
{return obj;};
explicit operator bool() const {
return ok_;
}
};
下面是抱怨访问问题的代码
template <typename T, typename U>
Sptr<T> static_pointer_cast(const Sptr<U> &sp) {
//do something
Sptr<U> answer;
answer.obj = sp.obj;
answer.ref = sp.ref;
answer.destroyData = sp.destroyData;
answer.ok_ = sp.ok_;
return answer;
}
当我使用以下代码编译时:
Sptr<Derived> sp(new Derived);
Sptr<Base1> sp2(sp);
// Sptr<Derived> sp3(sp2); // Should give a syntax error.
Sptr<Derived> sp3(static_pointer_cast<Derived>(sp2));
// Sptr<Derived> sp4(dynamic_pointer_cast<Derived>(sp2)); // Should give syntax error about polymorphism.
我已经把它变成了朋友功能。为什么它无法访问变量以及如何更正它?