c++ - 是否可以与类同时派生类属性?
问题描述
我要求做一个继承自 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 指针,因此是否可以使其具有与他所在的类相同的类型?
解决方案
唯一的选择是模板。作为一种方式 - 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
推荐阅读
- windows - 删除 Windows 并在 SSD 上重新安装
- makefile - Makefile:每次都重建具有中间先决条件的目标
- algorithm - 按特定列分组
- tensorflow - 如何将 keras.Model 的一部分提取到另一个模型中(tensorflow 2.1.0)?
- python - 如何将一维数组调整为多维数组
- vue.js - 为什么 Vuex getter 不能在这个简单的代码中工作?
- amazon-web-services - 确定性名称服务器地址
- node.js - Nodemailer“错误:Gmail API 凭据后缺少“PLAIN”凭据
- datetime - 在 Power Query 中转换具有多个日期列的 Excel 文件
- python - 除非将字符串写入文件,否则如何跳过字符串中的换行符?