繁体   English   中英

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

[英]inheritance of private member variable from class template

我做了一个类模板,如下所示,作为其他类的基础类,它可以正常工作。

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

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

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
    }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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