本文介绍了使用指向派生类中基类的指针访问受基类保护的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

似乎可以使用<$直接访问基类的成员c $ c> this 指针,而不是其他指针。

编译器是否将它们视为不同的实例化?

It seems that the member of the base class can be directly accessed using this pointer, but not the other pointers.
Does the compiler consider them as different instantiation?

推荐答案

是的,这是预期的行为。可以在派生类中访问基类的,但是仅通过派生类(或当前派生类的进一步派生类)(包括 this )类型的对象。这意味着您无法通过指向基类的指针访问受保护的成员。

Yes, this is expected behavior. Protected members of base class can be accessed in the derived class, but only via an object of a type that is the derived class (or the further derived class of current derived class) (including this). That means you can't access protected members via a pointer to base class.

1)...

2)由Base派生的任何类的成员,但仅当
对从Base(包括
this)派生的类型的对象进行操作

2) by the members of any class derived from Base, but only when operating on an object of a type that is derived from Base (including this)

这篇关于使用指向派生类中基类的指针访问受基类保护的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 09:20