gpt4 book ai didi

c++ - 从两个模板参数多重继承的奇怪?

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:25 24 4
gpt4 key购买 nike

#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。你能解释一下这种行为吗?

最佳答案

元素 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com