[英]Why the derived class cannot access protected base class members?
I have a base class (VectorRaw) and a derived class (Vector). 我有一个基类(VectorRaw)和一个派生类(Vector)。
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. 我在基类的构造函数中使用new运算符创建内存缓冲区,然后将new放置在派生类的构造函数中以在其中放置元素。
The base class has its virtual destructor which cleans up if something in the constructor of the derived class goes wrong. 基类具有其虚拟析构函数,如果派生类的构造函数中的某些操作出现问题,则该虚构析构函数将清除。
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. 当我尝试编译它时,出现一个错误:所有基类的成员(
begin, end, end_of_reserved
)在所有派生类的函数中都超出范围。
What am I doing wrong? 我究竟做错了什么?
Here's my code: 这是我的代码:
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);
}
};
Since your base class is a template class, you need to access the members through the this
pointer: 由于您的基类是模板类,因此您需要通过
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 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.
有关更多详细信息,请参见此答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.