c++ - 无法访问模板基类中的变量

标签 c++ templates inheritance g++

<分区>

我想访问父类中的 protected 变量,我有以下代码并且编译正常:

class Base
{
protected:
    int a;
};

class Child : protected Base
{
public:
    int b;
    void foo(){
        b = a;
    }
};

int main() {
    Child c;
    c.foo();
}

好的,现在我想把所有的东西都模板化。我将代码更改为以下内容

template<typename T>
class Base
{
protected:
    int a;
};

template <typename T>
class Child : protected Base<T>
{
public:
    int b;
    void foo(){
        b = a;
    }
};

int main() {
    Child<int> c;
    c.foo();
}

出现错误:

test.cpp: In member function ‘void Child<T>::foo()’:
test.cpp:14:17: error: ‘a’ was not declared in this scope
             b = a;
                 ^

这是正确的行为吗?有什么区别?

我使用 g++ 4.9.1

最佳答案

呵呵,我最喜欢的 C++ 怪癖!

这会起作用:

void foo()
{
   b = this->a;
//     ^^^^^^
}

非限定查找在这里不起作用,因为基础是模板。 That's just the way it is ,并归结为有关如何翻译 C++ 程序的高度技术细节。

关于c++ - 无法访问模板基类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31231875/

相关文章:

C++ 使用 ccfits 读取适合文件

c++ - 静态字段初始化的模板部分特化

"subclass"中的 Javascript 构造函数,正确的表示法?

c++方法参数给出意外输出

C++ 读取多列文件

c++ - 为什么我需要在用户为它赋值之前初始化这个变量?

c++ - 工厂和单例模式 : undefined reference

c++ - 如何使用 Google Mock 模拟模板化方法?

c# - 继承构造函数问题

C++如何创建创建派生类对象的基类,并访问基类的私有(private)成员?