accessing protected members of superclass in C++ with templates(使用模板访问 C++ 中超类的受保护成员)
问题描述
为什么 C++ 编译器不能识别 g() 和 b 是 Superclass 的继承成员,如以下代码所示:
Why can't a C++ compiler recognize that g() and b are inherited members of Superclass as seen in this code:
template<typename T> struct Superclass {
protected:
int b;
void g() {}
};
template<typename T> struct Subclass : public Superclass<T> {
void f() {
g(); // compiler error: uncategorized
b = 3; // compiler error: unrecognized
}
};
如果我简化 Subclass 并且只是从 Subclass 继承然后它编译.当将 g() 完全限定为 Superclass 和 Superclass 时,它也会编译.我使用的是 LLVM GCC 4.2.
If I simplify Subclass and just inherit from Subclass<int> then it compiles. It also compiles when fully qualifying g() as Superclass<T>::g() and Superclass<T>::b. I'm using LLVM GCC 4.2.
注意:如果我在超类中公开 g() 和 b ,它仍然会失败并出现相同的错误.
Note: If I make g() and b public in the superclass it still fails with same error.
推荐答案
这可以通过使用 using 将名称拉入当前范围来修改:
This can be amended by pulling the names into the current scope using using:
template<typename T> struct Subclass : public Superclass<T> {
using Superclass<T>::b;
using Superclass<T>::g;
void f() {
g();
b = 3;
}
};
或者通过this指针访问来限定名称:
Or by qualifying the name via the this pointer access:
template<typename T> struct Subclass : public Superclass<T> {
void f() {
this->g();
this->b = 3;
}
};
或者,正如您已经注意到的,通过限定全名.
Or, as you’ve already noticed, by qualifying the full name.
之所以有必要这样做,是因为 C++ 不考虑用于名称解析的超类模板(因为它们是从属名称并且不考虑从属名称).它在您使用 Superclass 时有效,因为它不是模板(它是模板的实例化),因此它的嵌套名称不依赖 名字.
The reason why this is necessary is that C++ doesn’t consider superclass templates for name resolution (because then they are dependent names and dependent names are not considered). It works when you use Superclass<int> because that’s not a template (it’s an instantiation of a template) and thus its nested names are not dependent names.
这篇关于使用模板访问 C++ 中超类的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用模板访问 C++ 中超类的受保护成员
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
