【问题标题】:child class not able to access parent member [duplicate]子类无法访问父成员[重复]
【发布时间】:2018-07-22 15:57:57
【问题描述】:

我在基类中创建了一个变量,它是模板的向量,但我无法从派生类访问该成员,有人可以解释一下吗?

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

/*
 * 
 */
template <typename T>
class Apple{
protected:
public:
    vector<T> vec;
    virtual void foo(T node) =0;
};

template <typename T>
class Ball:public Apple<T>{
public:
    void foo(T node){
        cout<<"hahaha\n";
        vec.push_back(node);/* I GET COMPILATION ERROR HERE"vec was not declared in this scope"*/
    }
};

int main(int argc, char** argv) {
    Ball<int> b;
    b.foo(10);
    return 0;
}

【问题讨论】:

  • "I GET COMPILATION ERROR HERE" - 是因为您不想让我们知道它是什么而未共享错误吗?
  • 不是私人使用this-&gt;vec
  • 发布的代码编译得很好。我标记为不可重现。
  • 这个might 很有帮助,但我认为它不适用,因为vec 是一个从属名称。
  • @UKMonkey 我无法用GCC 7.2Clang 5.0 编译它(完全按原样复制/粘贴)。这是在什么编译器上工作的?

标签: c++ oop inheritance


【解决方案1】:

您尚未在基类中创建任何私有成员。 要解决该错误,您可以将产生编译错误的行替换为: 苹果::vec.push_back(node); 要么 this->vec.push_back(node)

【讨论】:

    【解决方案2】:

    成员vec 属于模板参数dependent type,因此编译器需要一些帮助,例如:

    this->vec.push_back(node);
    

    或使用限定名:

    Apple<T>::vec.push_back(node)
    

    感谢@Avran Borborah - Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?

    规则如下:在查找非依赖名称(如 f)时,编译器不会查看依赖基类(如 B&lt;T&gt;)。

    这并不意味着继承不起作用。 ...

    【讨论】:

    猜你喜欢
    • 2015-08-06
    • 2010-11-09
    • 2011-11-03
    • 2018-12-31
    • 2014-07-13
    • 2013-09-25
    • 2016-07-21
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多