gpt4 book ai didi

c++ - 覆盖 C++ 派生类中的数据成员

转载 作者:搜寻专家 更新时间:2023-10-31 00:35:59 24 4
gpt4 key购买 nike

我有疑问,用C++重新定义。我在 Derived 类中分配内存,因此我需要在 Base 类中保留此内存。因此,我需要考虑 Base 类中的属性与 Derived 类中的属性相同,我不知道这在 C++ 中是否可行。

class Base {
protected:
float * a;
Base() {}
public:
virtual void reset() {
a = 0;
}
virtual void exec() {
printf("Memory a: %x\n",a);
}
};

class Derivada: virtual public Base {
protected:
float * a;
Derivada() {}
virtual void reset() {
a = new float[256];
}
};

int main() {
Derivada *hija= new Derivada();
hija->reset();
hija->exec();
delete hija;
}

我真的需要重载,因为它是我真正问题的一个例子。我有相同的测试(Derived an main, code),用于 CVS 的两个不同的类 Base,每个分支中一个。

在一个类Base中,我有这个属性,在另一个类Base中,我没有这个属性,所以我必须把它放在Derived类中进行编译。

我不想编写两个不同的测试代码,所以我需要重写该属性

最佳答案

你可以这样做(但需要 C++11):

#include <type_traits>

// A way to check for 'attr' data member presence/absence using SFINAE
template<class T> constexpr auto missing_attr(T) -> decltype(T::attr, bool())
{
return false;
}
constexpr bool missing_attr(...) { return true; }

struct Base { /* There might be (or not) a float data member 'attr' */ };

template<bool> struct Inject;
template<> struct Inject<true> { float attr = 0.0; };
template<> struct Inject<false> {};

struct Derived : public Base, protected Inject<missing_attr(Base())>
{
void do_something_with_attr()
{
// Derived has only one 'float attr' (it can be from Base or from Inject).
a *= a;
}
};

还有其他方法可以检测数据成员是否存在,例如member detector idiom (C++03 兼容)。

关于c++ - 覆盖 C++ 派生类中的数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22756502/

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