#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
可以看到,虽然Element1和Mix中的
this
是相同的,但对于Element2而言并非如此。这是为什么?另外,我希望可以从基类访问e1和e2。你能解释这种行为吗? 最佳答案
元素Mix
包含Element1
和Element2
。这些-也许是专门对齐的实现-依次写在内存中。如果您将Mix
用作Element1
,则它将指向两者中的第一个(尺寸为Element1
),如果将其用作Element2
,它将指向第二个(尺寸为Element2
),如果您将其用作Mix
,它将指向基址,该基址与Element1
的基址相同,但具有不同的大小(至少Element1
的大小+ Element2
的大小)。
编辑:您也可以通过输出大小来验证这一点:
#包括
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 << " + " << sizeof(*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 << " + " << sizeof(*this) << " in Element1" << endl;
}
unsigned int e1;
};
class Element2
{
public:
Element2(unsigned int e) : e2(e)
{
cerr << "This is " << this << " + " << sizeof(*this) << " in Element2" << endl;
}
unsigned int e2;
};
int main(int argc, char** argv)
{
Mix<Element1, Element2> m;
}
输出:
This is 0x7fffc9cad310 + 4 in Element1
This is 0x7fffc9cad314 + 4 in Element2
This is 0x7fffc9cad310 + 8 in Mix
E1: 1, E2: 2
关于c++ - 从两个模板参数具有多重继承的可能性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17596171/