【问题标题】:Pure virtual functions with templated inheritance [duplicate]具有模板化继承的纯虚函数[重复]
【发布时间】:2017-02-05 22:12:10
【问题描述】:

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

//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。

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

【问题讨论】:

  • 使用this-&gt;xthis-&gt;y
  • 这里使用this是多余的。
  • 你也可以使用A&lt;num&gt;::xA&lt;num&gt;::y或者typedef A&lt;num&gt; base然后base::x
  • 您的代码是正确的。你从哪里得到错误?
  • @Raindrop7 不,它不是多余的,它是必需的。

标签: c++ templates inheritance


【解决方案1】:

由于您使用模板继承,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;
    }
};

【讨论】:

    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2015-08-07
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多