【问题标题】:Why the derived class cannot access protected base class members?为什么派生类不能访问受保护的基类成员?
【发布时间】:2013-03-05 09:07:23
【问题描述】:

我有一个基类 (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);
    }
};

【问题讨论】:

    标签: c++ inheritance namespaces


    【解决方案1】:

    由于你的基类是模板类,你需要通过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

    【讨论】:

    • 有趣!我实际上试过这个,但后来我的编译器抱怨 operator new(size_t) 并建议使用 operator new(size_t, void*) 不分配任何存储
    • 您使用的非布局运算符错误。将begin = (T*) operator new (2 * size * sizeof(T)); 更改为begin = new T[2 * size];operator delete (begin); 更改为delete[] begin;
    • @RemyLebeau,你能解释一下区别吗?在我看到的 operator new[] 的文档中:“默认定义通过调用 operator new 来分配内存:::operator new (size)”
    猜你喜欢
    • 2019-01-20
    • 2014-08-27
    • 2016-12-07
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多