gpt4 book ai didi

c++ - 从类模板继承私有(private)成员变量

转载 作者:行者123 更新时间:2023-11-28 04:29:57 24 4
gpt4 key购买 nike

我制作了一个如下所示的类模板,作为其他类继承的基类,它会按预期正常工作。

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

我不明白为什么应该允许这样的事情......编译器不应该对此触发错误消息吗? (派生类不应该修改基类的私有(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

关于c++ - 从类模板继承私有(private)成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53213443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com