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

4

1 回答 1

1

该元素Mix包含一个Element1和一个Element2。这些——也许是专门对齐的实现——一个接一个地写在内存中。如果你使用Mixas Element1,这将指向两个中的第一个(大小为Element1),如果你使用它,Element2它将指向第二个(大小为Element2),如果你使用它,Mix它将指向基地址,这与Element1s 基地址相同,但具有不同的大小(至少大小为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
于 2013-07-11T14:52:40.640 回答