This question already has answers here:
Why do I have to access template base class members through the this pointer?

(3个答案)


3年前关闭。




我遇到了最奇怪的错误,也不知道我在做什么错。
template <bool X>
struct A {
    int x;
};

template <bool X>
struct B : public A<X> {
    B() { x = 3; } // Error: 'x' was not declared in this scope.
};

考虑到我公开继承了x,我不明白我怎么可能看不到B中的A

同时,此代码编译:
template <bool X>
struct A {
    int x;
};

template <bool X>
struct B : public A<X> {};

int main() {
    B<false> b;
    b.x = 4;
};

我正在使用g++ 7.0.1进行编译。

编辑:看来,如果我引用x的全名,则代码会编译,如下所示:
B() { A<X>::x = 3; }

但为什么?

最佳答案

编译器不知道如何找到x。使用this->X,它将起作用。

编译器在struct B上进行第一次传递时,尚不知道template参数。通过使用this指针,您将名称查找推迟到第二遍。

关于c++ - 具有模板阴影的继承继承成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46268613/

10-11 23:06
查看更多