无法访问基类字段

Can't access base class field

本文关键字:字段 基类 访问      更新时间:2023-10-16

>我创建了一个基类,如下所示:

#include <cstdint>
#include <iterator>
#include <cstdint>
#include <vector>
#include <initializer_list>
class PSBaseObject
{
    protected:
        inline std::int32_t* size_ptr(void* Data) { return reinterpret_cast<std::int32_t*>(Data) - 1; }
        inline const std::int32_t* size_ptr(void* Data) const { return reinterpret_cast<std::int32_t*>(Data) - 1; }
    public:
        PSBaseObject() {}
        virtual ~PSBaseObject() {}
};
template<typename T>
class PSObject : public PSBaseObject
{
    protected:
        T Data;
        inline std::int32_t* size_ptr() { return reinterpret_cast<std::int32_t*>(&Data[0]) - 1; }
        inline const std::int32_t* size_ptr() const { return reinterpret_cast<std::int32_t*>(&Data[0]) - 1; }
    public:
        PSObject() { *size_ptr(&Data[0]) = 0; *(size_ptr(&Data[0]) - 1) = -1; }
        virtual ~PSObject() {}
};

然后我从PSObject(不是PSBaseObject)继承,如下所示:

template<typename T>
class PSArray : public PSObject<std::vector<T, CustomAllocator<T>>>
{
    private:
        typedef std::vector<T, CustomAllocator<T>> underlying_type;
    public:
        typedef std::size_t                                                 size_type;
        typedef std::ptrdiff_t                                              difference_type;
        typedef T*                                                          pointer;
        typedef const T*                                                    const_pointer;
        typedef T&                                                          reference;
        typedef const T&                                                    const_reference;
        typedef T                                                           value_type;
        typedef typename underlying_type::iterator                          iterator;
        typedef typename underlying_type::iterator::const_iterator          const_iterator;
        typedef std::reverse_iterator<const_iterator>                       const_reverse_iterator;
        typedef std::reverse_iterator<iterator>                             reverse_iterator;
        explicit PSArray() : Data(CustomAllocator<T>()) { *size_ptr() = 0; }
        explicit PSArray(size_type size) : Data(size, CustomAllocator<T>()) { *size_ptr() = size - 1; }
        explicit PSArray(size_type size, const T &value) : Data(size, std::forward<decltype(value)>(value), CustomAllocator<T>()) { *size_ptr() = size - 1; }
};

int main()
{
}

它告诉我:

error: class ‘PSArray<T>’ does not have any field named ‘Data’

为什么它看不到其基类中的"数据"字段?还有没有办法将我的 typedefs 移动到基类并让子类仍然能够看到它们?

不能在派生类中初始化基类的Data字段;您需要提供一个采用 T 类型的对象的构造函数,然后基类构造函数可以使用该值初始化Data