繁体   English   中英

为什么派生类无法访问受保护的基类成员?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM