【问题标题】:Accessing public inherited Template data members [duplicate]访问公共继承的模板数据成员[重复]
【发布时间】:2011-04-06 15:55:30
【问题描述】:

我需要澄清一下为什么我们需要范围解析运算符或this 指针来访问从模板基类公开继承的成员。 据我了解,这是为了增加清晰度,但this 如何增加任何进一步的清晰度,而不仅仅是指出它是该类的成员。

为了让我的问题更清楚,我添加了一些代码。

#include <iostream>
using namespace std;

template <class T, class A>
class mypair {
        public:
         T a, b;
  public:
    mypair (T first, T second)
      {a=first; b=second;}

        virtual void printA() 
        {   
        cout<<"A"<<a<<endl;
        cout<<"B"<<b<<endl;
        }   
};







template <class T, class A>
class next: mypair<T,A>
{
public:

        next (T first, T second) : mypair<T,A>(first, second)
        {   
        }   

        void printA() 
        {   
        cout<<"A:"<<mypair<T,A>::a<<endl; // this->a; also works 
        cout<<"B:"<<mypair<T,A>::b<<endl; // this-b;  also works
        }   

};


int main () {
  next<double,float>  newobject(100.25, 75.77);
  newobject.printA();
  return 0;
}

输出:

A:100.25
B:75.77

如果我删除范围(或此运算符),则会出现超出范围的错误。 但是为什么我们需要一个公开继承成员的范围。

对此有一些想法会很棒。

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    参考Name lookup - Using the GNU Compiler Collection (GCC)

    通过添加显式前缀 mypair&lt;T, A&gt;this-&gt;,您可以使 printA 模板参数依赖。然后在模板实例化阶段解析定义。

    【讨论】:

    • 有趣的阅读 那么这是只有模板的特例吗?
    • 只在模板类的函数中。
    猜你喜欢
    • 2012-10-26
    • 2013-05-04
    • 2016-02-21
    • 2011-03-03
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    相关资源
    最近更新 更多