无法访问基类字段
Can't access base class field
>我创建了一个基类,如下所示:
#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
。
相关文章:
- 如何避免在数据结构中包含存储为字段的类?
- 将字段(在类中)定义为引用的缺点是什么?
- 访问基类中直接受保护的字段
- 如何从具有多个对象/字段的类中调用方法函数
- 为什么在具有引用字段的类中隐式删除复制运算符
- 从测试程序访问共享库中具有静态私有字段的类
- Const 引用字段作为类中的只读属性C++
- C++多态性访问基类派生类字段
- 无法访问基类字段
- 如何从基类 c++ 复制字段
- 继承和复制构造函数-如何从基类初始化私有字段
- 构造以shared_ptr作为成员字段的类的正确语法是什么
- 如何将指向基类的指针保存到另一个类的字段
- 如何通过派生类的方法复制来设置基类字段
- 如何实现一系列使用非静态类字段的类成员回调
- 如何设计具有"annotated"字段的类?
- 在Visual c++ 2010中不能使用default_random_engine字段创建类
- 通过转换基类指针来设置派生类字段
- 这个>字段和类::字段之间的区别?
- 如何在 c++ 中将字段从类传递到函数