无法访问基类字段

时间:2014-02-18 04:35:22

标签: c++ inheritance

我创建了一个类似的基类:

#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’

为什么它没有从基类中看到“数据”字段?还有一种方法可以将我的typedef移动到基类并让子类仍能看到它们吗?

1 个答案:

答案 0 :(得分:1)

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