#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
如您所见,虽然{1}在Element1和Mix中是相同的,但对于Element2则不然。这是为什么?此外,我希望能从基类访问e1和e2。你能解释一下这种行为吗?
答案 0 :(得分:1)
元素Mix
包含Element1
和Element2
。这些 - 也许是实现特定对齐 - 在内存中相互写入。如果您使用Mix
作为Element1
,则会指向两个中的第一个(大小为Element1
),如果您将其用作Element2
,它将指向第二个(大小为Element2
),如果您将其用作Mix
,它将指向基址,该地址与Element1
的基址相同,但具有不同的大小(至少Element1
+ Element2
的大小。
编辑:您也可以通过输出尺寸来验证这一点:
#include
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