不从基类C ++继承

时间:2013-10-02 16:51:22

标签: c++ inheritance

让我直截了当。这是一个面试问题,到目前为止我无法解决。考虑两个班级

class A
{
     public : virtual int f() { };
              int a;
 }

class B : public A
{

     public : virtual int g() { };
              int b;
}

当被问及A和B的大小我正确地说8和12.下一个问题是如何定义B类,使它忽略从A派生的前8个字节。他说这是可能的。我仍然无法理解它是如何可能的。谁能解释一下如何做到这一点?

编辑:真正的问题不是找到班级的大小,而是跟进。

2 个答案:

答案 0 :(得分:4)

我不确定提问者的期待是什么答案,但这里有一些可能的解决方案:

让'A'成为指针:

//Only takes 4 or 8 bytes (32 bit vs 64 bit code) for 'A', regardless of 'A's actual size, but must point to an 'A' located elsewhere in memory with the full size.
class B
{
   A *a; //Only 4 bytes.
   int b;
};

让'A'静态:

//Doesn't assume any of 'A's size, but all instances of 'B' shares a single instance of 'A'.
class B
{
    static A a;

    int b;
};

将'A'传递给'B'的功能:

//Pass in the reference to 'a' when needed, so multiple 'B's can share the same 'a' explicitly when desired.
class B
{
    void q(A &a) { this->b + a.a; return a.g(); }
};

让'A'和'B'没有虚拟表(可能是面试官的观点)

//By not having virtual functions, you save the (really small) cost of 4 bytes (8 bytes on 64 bit machines)
class A
{
public:
     int f() { }; //Not virtual
     int a;
}

class B : public A
{
public:
     int g() { }; //Not virtual
     int b;
}

它仍然会花费你A :: a的大小,除非你在B中重复使用'a'而不是B :: b,否则你无法避免这4个字节。并且重新使用一个变量来完全表示其他东西可能是一种非常糟糕的编程习惯的迹象。

统一A'a和B的变量并将函数放在一个单独的类中

class AB //Only 4 bytes total
{
   public:
   union
   {
       int a;
       int b;
   };

   void f();
   void g();
};

关于这个的坏主意是,你必须跟踪你是否应该访问'a'或'b',因为它们都占用相同的4个字节的内存,并且它们不能同时使用它在同一时间。

另一个坏处是,这表明班级有太多的责任。是A还是B?如果两者兼而有之,那么所有重要的问题应该是“为什么两者兼而有之?”。它应该有single-responsibility,而不是混合目的的monolith

让'A'成为模板,并继承自A<B>

template<typename TypeB>
class A
{
    int a;
};

//Saves the cost of the virtual table... not that that really matters.
class B : public A<B>
{
    int b;
};

最后一个被称为'curiously recurring template pattern'(CRTP) 我们的想法是,继承的“A<B>”可以从“B”调用访问变量和函数(如果将B的“this”指针传递给A的构造函数),“B”可以直接从“{”访问变量和函数。 {1}}”。

您继承了为'B'生成的模板'A'的编译时生成版本。

答案 1 :(得分:0)

这并没有直接回答采访者的问题,但操纵A和B继承的另一种可能方法是做这样的事情:

#include <iostream>
#include <memory>
#include <vector>
using namespace std;

//This concept was taken from a Going Native 2013 talk called "C++ Seasoning" given by Sean Parent
//
//Located here: (about 101 minutes into it)
//http://channel9.msdn.com/Events/GoingNative/2013/Cpp-Seasoning

//Polymorphism without inheritance.
//Permits polymorphism without using pointers or references,
//and allows them to be copied around easier (each instance is actually its own object) rather
//than accidentally shallow-copying when you wanted deep-copies.
//
//Every time Object::Print() is called, it calls
// Object::PrintableConcept::Print(), which virtually calls
// Object::PrintableModel<TYPE>::Print(), which calls your
// "derived" class that implements the Print() function, regardless
// of what that class inherits (if anything).
class Object //Class without inheritance or virtual.
{
    public:
    template<typename Type>
    Object(Type instance) : self(std::make_shared<PrintableModel<Type>>(std::move(instance)))
    { }

    //Calls the "inherited" function.
    void Print() const
    {
        self->Print();
    }

    private:
    struct PrintableConcept //The concept we want to polymorphably access.
    {
        virtual ~PrintableConcept() = default;
        virtual void Print() const = 0;
    };

    //The class that concretely models the concept,
    //and does the actual inheritting.
    template<typename Type>
    struct PrintableModel : public PrintableConcept
    {
        PrintableModel(Type instance) : data(std::move(instance)) { }

        //Every time 
        void Print() const override
        {
            this->data.Print();
        }

        Type data;
    };

    //This should be a unique_ptr, but you also need to make sure
    //you implement proper copy operators in this class and move support.
    std::shared_ptr<PrintableConcept> self;
};

class Whatever
{
    public:
    void Print() const { std::cout << "Whatever\n" << std::endl; }
};

class SomethingElse
{
    public:
    void Print() const { std::cout << "SomethingElse\n" << std::endl; }
};

class WidgetThing
{
    public:
    void Print() const { std::cout << "WidgetThing\n" << std::endl; }
};

typedef std::vector<Object> Document;

int main()
{
    Document document;
    document.emplace_back(Whatever());
    document.emplace_back(SomethingElse());
    document.emplace_back(WidgetThing());

    for(const auto &object : document)
    {
        object.Print();
    }

    return 0;
}

&LT;&LT;&LT; Run the code&gt;&gt;&gt;

这些类中没有一个实际上是从'Object'(或其他任何东西)继承的,但是可以在一个向量中互相交替使用,因为它们都实现了一个公共接口(PrintableConcept)对象访问是模板化的,但是对象本身不是模板,因此不会成为Object<something>Object<something-else>,这将是单独的类型。