首页 > 解决方案 > 是否可以与类同时派生类属​​性?

问题描述

我要求做一个继承自 ABR 的 Vec。此 ABR 有 3 个指针作为 ABR 类型的属性。我想知道这些指针的类型是否可以在没有模板参数的情况下派生为 Vec 时变为 Vec ?

这是一些代码来描绘它:

class Base
{
protected:
    Base* x;
public:
    Base(): x(nullptr){}
    Base* getVal() {return x;}
};

class Derived: public Base
{
private:
    int y;
public:
    Derived():Base(), y(-1) {}
    Derived(int Y): y(Y){}

    Derived* getVal() {return x;}
    void setVal(Derived *ptr){this->x = ptr;}
};

int main()
{
    Derived D(5), c(7),*ptrToC=&c;
    D.setVal(ptrToC);
    D.getVal();
}

此代码将在“D.getVal()”处返回错误,因为 x 仍然是 Base 指针,因此是否可以使其具有与他所在的类相同的类型?

标签: c++derived

解决方案


唯一的选择是模板。作为一种方式 - CRTP成语:

template <class T>
class Base
{
protected:
   Base* x;
public:
   Base() : x(nullptr) {}
   T* getVal() { return dynamic_cast<T*>(x); }

   virtual ~Base() {}
};

class Derived : public Base<Derived>
{
private:
   int y;
public:
   Derived() :Base(), y(-1) {}
   Derived(int Y) : y(Y) {}

   void setVal(Derived *ptr) { this->x = ptr; }
};

int main()
{
   Derived D(5), c(7), *ptrToC = &c;
   D.setVal(ptrToC);
   D.getVal();
}

另请注意,您的代码中没有多态性。您需要Base通过添加至少一个虚拟方法(fe 析构函数)来创建一个虚拟函数表。除非您当然想将 Base 转换为 Derived


推荐阅读