在C ++

时间:2017-02-11 21:31:15

标签: c++ inheritance

经历了我头脑中的多次迭代,我不知道"最好的"或者"最正确的"方法来解决这个问题。

设定:

  • 我有一个班级' A'提供给我。我无法改变这门课程。这个类有几个公共方法。
  • 我写过课程' B'这需要许多课程,并将它们作为一个控制,使用相同的方法名称使A和B在代码中可互换。
  • 我现在想写课程' C'可以上课#A'或者班级' B' (或将来使用相同的公共方法的其他类)执行更复杂的操作。

我试过写一个"超类" ' d'在C' C'可以继承' D'并提供所需的各种类型。但是' D'无法看到' C'私人变量。

我确定我只是想到这个结构错了,所以在这里弄清楚如何正确使用继承。给D类现在知道C类的类型,我不能强制它。 D也将具有许多需要使用' o'我试图避免为每种潜在的班级类型重新实施每一项。

我也确定这是一个常见问题,但我现在一直在寻找答案2天......

简化示例代码:

// Class A has been provided to me, and cannot be modified.
#include <classA.h>

class B {
  public:
    B(A *x, int num): z(x), n(num) {};

  int num(void) {return n;};
  // Other methods to operate on objects of class A as if they were a single
  // one, using same method names. Maybe somehow inheritance is better here?

  private:
    A *z;
    int n;
};


class D {
  public:
    D(void): s(5) {};

  // 'o' to be provided by child class, must have method 'num'
  void doThat(void) {return s+o.num();};  

  private:
    int s;
};

// So we can handle multiple types of devices that have the same public methods
// This is just a class to get the private object that superclass D will need
class C: public D {
  public:
    C(B *h): o(h) {};

  private:
    B *o;
};

A ar[2] = { A(1), A(2) };
B l(ar, 2);
C j(&l);

这让我得到了“&#39; o&#39;不在范围内。

Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"
sketch_feb11b.ino: In member function 'void D::doThat()':
sketch_feb11b:26: error: 'o' was not declared in this scope
  void doThat(void) {return s+o.num();};
exit status 1
'o' was not declared in this scope

我多年后重新回到C ++,所以我也愿意接受我现在没有正确处理问题。

2 个答案:

答案 0 :(得分:4)

您可以使用D

模板
button-release-event

答案 1 :(得分:0)

class D {
public:
  D(): s(5) {} 
  // Your child class must overload getter method getNum() 
  int doThat() {
     return s + getNum();
   }
private:
  int s;
  // pure virtual, must be overload
  virtual int getNum() = 0; 
...
};

class C : public D {
private:
  B* o;
   // overload pure func
  int getNum() override {
    return o->num();
  }
public:
  // Use default D ctor
  C(B* b) : D(), o(b) {}
...  
};

A ar[2] = { A(1), A(2) };
B l(ar, 2);
C j(&l);
j.doThat(); // return 5 + ar->num