#include <iostream>
using namespace std;
template <typename E1, typename E2>
class Mix : public E1, public E2
{
public:
Mix() : E1(1), E2(2)
{
// Set nothing here
cerr << "This is " << this << " in Mix" << endl;
print(cerr);
}
void print(ostream& os)
{
os << "E1: " << E1::e1 << ", E2: " << E2::e2 << endl;
// os << "E1: " << e1 << ", E2: " << e2 << endl; won't compile
}
};
class Element1
{
public:
Element1(unsigned int e) : e1(e)
{
cerr << "This is " << this << " in Element1" << endl;
}
unsigned int e1;
};
class Element2
{
public:
Element2(unsigned int e) : e2(e)
{
cerr << "This is " << this << " in Element2" << endl;
}
unsigned int e2;
};
int main(int argc, char** argv)
{
Mix<Element1, Element2> m;
}
现在,由于我们同样从两个模板参数类继承,我希望this
在两个构造函数中是相同的,但事实并非如此。这是运行日志:
This is 0x7fff6c04aa70 in Element1
This is 0x7fff6c04aa74 in Element2
This is 0x7fff6c04aa70 in Mix
E1: 1, E2: 2
如您所见,虽然this
在 Element1 和 Mix 中是相同的,但对于 Element2 则不是这样。这是为什么?此外,我希望能够从基类访问 e1 和 e2 。你能解释一下这种行为吗?