簡體   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