Sii*_*Sii 6 c++ inheritance templates
我需要澄清一个问题,为什么我们需要范围解析运算符或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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
A:100.25
B:75.77
Run Code Online (Sandbox Code Playgroud)
如果我删除范围(或此运算符),则超出范围错误.但为什么我们需要公开继承成员的范围.
对此的一些想法会很棒.