我有一个基类 (VectorRaw) 和一个派生类 (Vector)。
我在基类的构造函数中使用 operator new 创建一个内存缓冲区,然后在派生类的构造函数中放置 new 以在其中放置元素。
基类有它的虚拟析构函数,如果派生类的构造函数中出现问题,它会清理。
当我尝试编译它时,出现错误:所有基类的成员(begin、end、end_of_reserved
)都超出了所有派生类函数的范围。
我做错了什么?
这是我的代码:
template <typename T>
class VectorRaw {
protected:
T * begin;
T * end;
T * end_of_reserved;
VectorRaw(const size_t size) {
begin = (T*) operator new (2 * size * sizeof(T));
end = begin;
end_of_reserved = begin + 2 * size;
}
virtual ~VectorRaw<T> () throw() {
for (T * iter = begin; iter != end; ++iter) {
iter->~T();
}
operator delete (begin);
end_of_reserved = end = begin;
}
};
template <typename T>
class Vector : public VectorRaw<T> {
public:
Vector(const size_t size, const T& value) : VectorRaw<T>(size) {
for (end = begin; end != begin + size; ++end)
{
new (end) T (value);
}
}
bool Empty() const throw() {
return (begin == end);
}
};
最佳答案
由于你的基类是一个模板类,你需要通过this
指针来访问成员:
template <typename T>
class Vector : public VectorRaw<T> {
public:
Vector(const size_t size, const T& value) : VectorRaw<T>(size) {
for (this->end = begin; this->end != this->begin + size; ++this->end)
{
new (this->end) T (value);
}
}
bool Empty() const {
return (this->begin == this->end);
}
};
这对于推迟查找这些名称直到知道模板参数是必要的。它使它们成为依赖名称。参见 this answer了解更多详情。
关于c++ - 为什么派生类不能访问 protected 基类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15452948/