为什么派生类不能访问受保护的基类成员?
我有一个基类 (VectorRaw) 和一个派生类 (Vector).
I have a base class (VectorRaw) and a derived class (Vector).
我在基类的构造函数中使用operator new来创建内存缓冲区,然后在派生类的构造函数中放置new来放置元素.
I use operator new in the constructor of the base class to create a memory buffer and then placement new in the constructor of the derived class to place elements therein.
基类有它的虚析构函数,它会在派生类的构造函数出错时进行清理.
The base class has its virtual destructor which cleans up if something in the constructor of the derived class goes wrong.
当我尝试编译它时,有一个错误:所有基类的成员(begin、end、end_of_reserved
)在所有派生类的函数中都超出了范围.
When I try to compile it, there is an error: all of the base class' members (begin, end, end_of_reserved
) are out of scope in all derived classes' functions.
我做错了什么?
这是我的代码:
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
指针访问成员:
Since your base class is a template class, you need to access the members through the this
pointer:
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 is necessary to defer the lookup of these names until the template parameter is known. It makes them dependent names. See this answer for more details.