从类模板继承私有成员变量

时间:2018-11-08 17:48:23

标签: c++

我使一个类模板如下所示,作为其他类要继承的基类,并且可以按预期工作。

但是我的问题是,即使我将“ Operation”类的“ protected”更改为“ private”,代码仍然可以编译,即使Matmul(继承了“ Operation”类)正在修改名为“ edgeIn”的向量,声明为“私人”。

我不明白为什么应该允许这样的事情... 编译器是否应该触发此错误消息? (派生类不应修改基类的私有成员)

template<typename T>
class Operation{
private: //Would compile fine even if I change this to 'private!'
    class edge{
    public:
        edge(Tensor<T> tensor, Operation<T> &from, Operation<T> &to) {
            this->tensor = tensor;
            this->from = from;
            this->to = to;
        }
        Operation<T> from;
        Operation<T> to;
        Tensor<T> tensor;
    };
    std::vector<edge> edgeIn; //edges as inputs of this operation
    std::vector<edge> edgeOut; //edges as outputs of this operation
private:
    //disable copy constructor (NOT ALLOWED)
    Operation(Operation<T>& rhs) = default;
    //disable move operator (NOT ALLOWED)
    Operation<T>& operator=(Operation<T> &rhs) = default;
    int operationId;
};

template<typename T>
class Matmul: public Operation<T>{
public:
    Matmul(std::initializer_list<std::pair<Tensor<T>, Operation<T>>> args);
};

template<typename T>
//from Operation<T>, to This operation
Matmul<T>::Matmul(std::initializer_list<std::pair<Tensor<T>, Operation<T>>> args){
    for(auto elem: args){
        typename Operation<T>::edge info{elem.first, elem.second, *this};
        this->edgeIn.emplace_back(info); //modifying member of base class
    }
}

1 个答案:

答案 0 :(得分:1)

在您显示的代码中,它是允许的,因为它没有错。这是一个更简单的示例:

template <class Ty>
class base {
    int i; // private
};

template <class Ty>
class derived : base {
    void set(int ii) { i = ii; }
};

此时,如果您写

derived<int> di;
di.set(3); // illegal: i is not accessible

如您所料,您将获得访问错误。

但是原始模板没有错,因为代码可以做到这一点:

template <>
class base<int> {
public:
    int i;
};

现在您可以写

derived<int> di;
di.set(3);

没关系,因为ibase<int>中是公开的。你还是不会写

derived<double> dd;
dd.set(3); // illegal: i is not accessible