【问题标题】:'using Base<T>::func()' in derived class makes 'func' inaccessible outside of derived class'在派生类中使用 Base<T>::func()' 使派生类外部无法访问'func'
【发布时间】:2017-11-29 16:26:07
【问题描述】:

这是 C++。我有以下程序:

#include <iostream>

using namespace std;

template <typename T>
class Base {
public:
    T t;
    void use() {cout << "base" << endl;};
};

template <typename T>
class Derived: public Base<T> {
using Base<T>::use;

public:
   T x;
   void print() { use(); };

};

using namespace std;

int main() {

    Derived<float> *s = new Derived<float>();

    s->Base<float>::use(); // this is okay
    s->use();  // compiler complaints that "void Base<T>::use() is inaccessible"

    s->print(); // this is okay

    return 0;
}

Base::use() 不使用模板类型名 T。根据Why do I have to access template base class members through the this pointer?,我在 Derived 中使用了 'using Base::use',因此我可以在 Derived::print( )。但是,我不能再通过指向 Derived 的指针调用 use() 了。这是什么原因造成的?

【问题讨论】:

  • 您在 Derived 类的私有上下文中执行了 using

标签: c++ templates


【解决方案1】:

你需要有线路

using Base<T>::use;

Derivedpublic 部分中。

template <typename T>
class Derived: public Base<T> {

public:
   using Base<T>::use;
   T x;
   void print() { use(); };

};

Live demo.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-02
    • 2013-08-16
    • 2017-11-28
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    相关资源
    最近更新 更多