依赖模板基础的受保护成员
Protected members of dependent template bases
所以我通读了这个问题,我理解模板中依赖名称的前提,以及有时必须如何用this->
限定方法以确保编译器可以正确找到它,但是我遇到了一个我无法弄清楚如何解决的情况。具体来说,当该方法所属的对象与*this
的类型相同时,但它是不同的对象(可能属于不同的子类(。例如:
#include <iostream>
template<class T>
class A
{
protected:
virtual void foo() = 0;
};
template<class T>
class B : public A<T>
{
};
template<class T>
class C : public B<T>
{
protected:
void foo() override
{
std::cout << "Hello, world" << std::endl;
}
};
template<class T>
class D : public B<T>
{
protected:
void foo() override
{
B<T> *b = new C<T>();
b->foo(); // error: 'void A<T>::foo() [with T = int]' is protected
}
public:
void bar()
{
this->foo();
}
};
int main()
{
D<int> d;
d.bar();
}
鉴于这个继承层次结构,以及调用b->foo();
时的错误,调用该函数的正确方法是什么?据我了解,原则上它应该可以通过D
中的代码访问,因为它是基类的受保护成员,但它因模板系统而变得复杂。
您的问题与模板无关,如果您删除所有模板代码,则会出现相同的错误。
将成员声明为protected
意味着您只能从同一(直接(类访问该成员;因此,虽然D
和C
可能都派生自B
,但它们都是明显不同的类型,而不是直接B
,因此D
和C
无法访问B
的另一个实例的受保护成员。
例如,使用您发布的一些代码获取以下代码:
class D : public B
{
public:
void baz(D& d, B& b)
{
foo(); // ok: calls this->foo();
d.foo(); // ok: type of `d` is `D`, same class
b.foo(); // error: can't access protected member
}
};
在代码中,将B* b = new C();
更改为D
类中的B* b = new B();
仍会遇到相同的错误,尝试访问受保护的成员。如果将其更改为D* b = new D();
,则错误将消失,因为b
现在与它所在的类的类型相同。
要解决此错误,您可以声明D
B
的 friend ,但这会带来其他需要考虑的问题,并且您必须为要访问的每个类添加一个转发/朋友声明foo
:
template < class T >
class D;
template <class T>
class B : public A<T>
{
friend class D<T>;
};
但是,鉴于您发布的代码,人们倾向于将bar
函数移出D
并将其放在B
中,然后您不必使用前向声明,并且您的大部分代码保持不变:
template <class T>
class B : public A<T>
{
public:
void bar()
{
this->foo();
}
};
// Then in your D class, change the call from `foo` to `bar`
template <class T>
class D : public B<T>
{
protected:
void foo() override
{
B<T> *b = new C<T>();
b->bar();
}
};
这可能不适合您的特定方案,但最终您的问题基本上归结为需要public
访问权限。
希望能有所帮助。
相关文章:
- C++:无法访问声明的受保护成员
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 同一模板类但模板类型的受保护成员
- 派生类无法访问基类的受保护成员
- 继承期间受保护成员的皮条
- 如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?
- 是否可以基于私有/受保护成员分配类枚举?
- 依赖模板基础的受保护成员
- 无法从派生类型的作用域访问另一个实例的受保护成员
- 为什么我无法使用受保护/私有继承访问派生实例中基类的受保护成员?
- 将对象强制转换为派生类以访问父类的受保护成员
- 使从一个基类派生的类能够使用继承的受保护成员
- 派生类如何使用基类的受保护成员
- 访问派生类C++中的受保护成员
- 访问基类的受保护成员
- 如何访问多个继承类中的受保护成员
- 如何从另一个类的基类访问派生类中的受保护成员
- 无法访问派生类中的基本受保护成员!(在虚函数中)
- 如何通过派生类访问基类的受保护成员?
- 如果孩子不需要父母班级的所有受保护成员,这是不好的班级设计吗?