![](/img/trans.png)
[英]Why can't I access protected members of base class in derived instances using protected/private inheritance?
[英]Why the derived class cannot access protected base class members?
我有一個基類(VectorRaw)和一個派生類(Vector)。
我在基類的構造函數中使用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);
}
};
必須推遲對這些名稱的查找,直到知道模板參數為止。 它使它們成為從屬名稱 。 有關更多詳細信息,請參見此答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.