[英]Why is this class's own protected member inaccessible from a template method?
Why can I not access the protected members from a template method of a class? 为什么不能从类的模板方法访问受保护的成员?
I may be missing some special friend declaration here but it eludes me. 我可能在这里错过了一些特殊的朋友声明,但这使我难以理解。 I feel like I should be able to do this.
我觉得我应该能够做到。
The error is: 错误是:
error: 'char* ClassB<char>::a' is protected
Example source: 来源示例:
template<typename T>
class ClassA;
template<typename T>
class ClassB {
protected:
T* a;
public:
ClassB()
: a(0) {}
template<typename U>
ClassB(const ClassB<U>& other)
:
// error: ‘char* ClassB<char>::a’ is protected
a(other.a) {}
};
////
template<typename T>
class ClassA : public ClassB<T> {
public:
ClassA() {}
};
////
namespace name {
typedef ClassA<char> A;
typedef ClassB<const char> B;
}
int main() {
name::A a;
name::B b = a;
return 0;
}
You can't do it for the same reason that ClassA
cannot access the protected/private members of ClassB
. 出于相同的原因,您不能这样做,因为
ClassA
无法访问ClassB
的受保护/私有成员。 The fact that templated classes share a common name doesn't really matter to them. 模板类共享一个通用名称这一事实对他们来说并不重要。
ClassB<T>
and ClassB<U>
treat each other like entirely different classes and so their members aren't accessible to each other. ClassB<T>
和ClassB<U>
像对待完全不同的类一样对待彼此,因此它们的成员彼此不可访问。
The reason for this becomes clearer when you realize you can specialize templated classes, which means that it's possible to have implementations of ClassB
that do not have a member named a
(or do have a member named a
, but use it in an entirely different way, and so it shouldn't be accessed). 当您意识到可以对模板化的类进行专门化时,其原因变得更加清楚,这意味着可以实现不具有名为
a
的成员(或确实具有名为a
的成员,但以完全不同的方式使用它)的ClassB
实现。 ,因此不应访问它)。
The fact is that ClassB<T>
and ClassB<U>
are different classes (unless T = U
, but that's not generally true and so the compiler can't rely on that assumption). 事实是
ClassB<T>
和ClassB<U>
是不同的类(除非T = U
,但这通常不是正确的,因此编译器不能依赖该假设)。 Hence, they can't access each other. 因此,他们不能互相访问。
This is an abstraction feature of the language. 这是该语言的抽象功能。 Just like two independent classes,
ClassB<T>
and ClassB<U>
treat each other like they are not related and are different classes and so they cannot access private
and protected
members of each other. 就像两个独立的类一样,
ClassB<T>
和ClassB<U>
彼此对待,就像它们没有关联并且是不同的类一样 ,因此它们无法访问彼此的private
成员和protected
成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.