【发布时间】:2017-10-01 01:28:23
【问题描述】:
考虑以下代码:
#include <iostream>
using std::endl;
using std::cout;
template<typename T>
class B{
protected:
T value;
B* ptr;
public:
B(T t):value(t), ptr(0){}
};
template<typename T>
class D: public B<T>{
public:
void f();
D(T t):B<T>(t){}
};
template<typename T>
void D<T>::f(){
cout << this->value << endl; //OK!
this->ptr = this;
cout << this->ptr->value << endl; //error! cannot access protected member!!
B<T>* a = this;
cout << a->value <<endl; //error! cannot access protected member!!
}
int main(){
D<double> a(1.2);
a.f();
return 0;
}
似乎可以使用this指针直接访问基类的成员,但不能使用其他指针。
编译器是否将它们视为不同的实例化?
【问题讨论】:
-
这和模板有什么关系?
标签: c++ protected access-rights