c++ - 具有模板化继承的纯虚函数

标签 c++ templates inheritance

我正在尝试使用模板化派生类来实现多态性。见下文:

//templated base class
template <class num> class A{
protected:
    num x;
    num y;

public:
    A( num x0 = 0, num y0 = 0) {
       x = x0;
       y = y0;
    }
    virtual void print_self() = 0;

};

//derived class
template < class num > class B: public A < num > {
   public:
      B( num x1 = 0, num y1 = 0):shape < num > ( x1 , y1 ) { }
      void print_self(){
          std::cout << "x is " << x << " and y is " << y << endl;
      }
};

基类具有纯虚函数 print_self()。当尝试在派生类中定义函数时,我收到以下错误:

'x' was not declared in this scope

y 也一样。 因此,派生类无法访问变量 x 和 y,即使它被列为 protected 。

是否有其他方法来定义 print_self(),或者这根本不可能?如果不可能,您能建议另一种方法吗?

最佳答案

由于您使用的是模板化继承,因此 xy 的存在取决于模板参数。换句话说,this 指针的基类部分成为依赖名称。您必须显式使用 this 指针或使用 using。

template<typename num>
struct B : A<num> {
    using A<num>::x;
    using A<num>::y;

    void print_self(){
        std::cout << "x is " << x << " and y is " << y << endl;
    }
};

或者甚至:

template<typename num>
struct B : A<num> {
    void print_self() {
        std::cout << "x is " << this->x << " and y is " << this->y << endl;
    }
};

关于c++ - 具有模板化继承的纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057921/

相关文章:

c++ - 当用作模板参数时,C++编译器不区分类型和函数名称

c++ - Windows 上的堆栈 - 它在哪里?

java - 如何取消忽略 SWIG 中模板化类的特定方法?

c++ - 包装 map 访问,聪明还是愚蠢?

ios - 如何在我正在子类化的类中返回 Swift 中的泛型类型

c++ - 浮点格式会受到大端和小端的影响吗?

c++ - 无法将 int 应用于 partial_apply 的结果

c++ - 在结构中使用模板

java - 从 Java 8 中的 Function 继承的命名具体接口(interface)

inheritance - 非结构类型中的接口(interface)继承