gpt4 book ai didi

c++ - 无法访问基类字段

转载 作者:行者123 更新时间:2023-11-28 07:05:22 30 4
gpt4 key购买 nike

我像这样创建了一个基类:

#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 移动到基类并让子类仍然能够看到它们吗?

最佳答案

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

关于c++ - 无法访问基类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21844468/

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