本文介绍了访问公共继承的Template数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要澄清一个问题,为什么我们需要范围解析运算符或this指针来访问模板基类的公共继承成员.据我了解,这是为了增加清晰度,但是this怎样增加清晰度,而不仅仅是指出它是该类的成员.

I require some clarification on the question why do we need the scope resolution operator or this pointer to access publicly inherited members from a template base class.As I understand it is for adding clarity but then how does this add any further clarity than just point that it is a member of the class.

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

To make my question clearer I have added some code.

#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

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

If i remove the scope(or this operator) then the out of scope error comes.But why do we need a scope for publicly inherited members.

对此有一些想法.

推荐答案

请参阅名称查找-使用GNU编译器集合(GCC)

通过添加显式前缀mypair<T, A>this->,可以使printA模板参数相关.然后在模板实例化阶段解析这些定义.

By adding explicit prefix mypair<T, A>, or this->, you make printA template argument dependent. Then the definitions will be resolved during template instantiation stage.

这篇关于访问公共继承的Template数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:34