【问题标题】:C++ inherit template class: hidden member variable [duplicate]C ++继承模板类:隐藏成员变量[重复]
【发布时间】:2018-11-15 16:24:21
【问题描述】:

为什么下面的代码无法编译?

#include <iostream>
template <class T>
class A
{
  public:
  T data;
};

template<typename T>
class B : public A<T>
{
 public:
 void foo(){printf("%d\n", data);}
};

int main() 
{
  B<int> b;
}

错误:

bla.cpp: In member function ‘void B<T>::foo()’:
bla.cpp:14:30: error: ‘data’ was not declared in this scope
void foo(){printf("%d\n", data);}

似乎成员变量“data”由于某种原因被隐藏了。

【问题讨论】:

    标签: c++


    【解决方案1】:

    你可以通过this访问base的成员变量:

    this->data;
    

    【讨论】:

    • 感谢这解决了问题,但这感觉很奇怪。如果 A 和 B 不是模板类,我就不必这样做。这是为什么呢?
    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2010-09-05
    相关资源
    最近更新 更多