简体   繁体   English

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

[英]Override a data member in a C++ derived class

I have an doubt, with C++ redefinition. 我对C ++重定义有疑问。 I assign memory in Derived class, so I need that this memory is reserved in Base class. 我在派生类中分配内存,因此我需要在基类中保留该内存。 So, I need considered that the attibute in the Base class is the same that the attribute in the Derived class, and I don't know is that is possible in C++. 因此,我需要考虑一下,基类中的属性与派生类中的属性相同,我不知道这在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;
}

I really need do overloading , because it is an example of my real problem. 我确实需要重载 ,因为这是我真正的问题的一个例子。 I have the same test (Derived an main, code), for two different class Base, one in each branch, of my two branchs, of CVS. 对于两个不同的Base类,我对CVS的两个分支中的每个分支都有一个相同的测试(派生一个主代码)。

In one of this class Base, I have this attributes, an in the other class Base, I don't have this attributes, so I have to put it, in Derived class, for compiling. 在一个此类Base中,我具有此属性,在另一个类别Base中,我没有此属性,因此必须将其放在Derived类中进行编译。

I wouldn't like to have to make two different test codes, so I need override the attribute 我不想做两个不同的测试代码,所以我需要覆盖属性

Do not redeclare the member the the derived class. 不要将成员重新声明派生类。 The word "protected" ensures visibility. “受保护”一词可确保可见性。

If you redeclare the member, you will have a new member. 如果重新声明成员,则将有一个新成员。 This is called shadowing. 这称为阴影。 See, eg 参见,例如

You could do something like this (but requires C++11): 您可以执行以下操作(但需要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;
  }
};

There are other ways to detect if a data member exists, eg the member detector idiom (C++03 compatible). 还有其他方法可以检测数据成员是否存在,例如, 成员检测器习惯用法 (与C ++ 03兼容)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM