使用抽象类的类和创建实现此抽象类的对象

时间:2018-04-22 15:58:20

标签: c++ c++11

我将首先发布我目前拥有的代码。我试图尽可能地减少它,但由于我对C ++没有那么有经验,我不知道我是否可能遗漏了很多或只是展示了很多代码。

class IBehavior {
public:
  virtual void DoIt() = 0;
};

class BehaviorA : public IBehavior {
  void DoIt() {
      cout << "Behavior: A\n";
  };
};

class BaseOfAB {
  IBehavior behavior;

  void DoIt() {
      behavior.DoIt();
  };
};

class A : public BaseOfAB {
  A() {
    BehaviorA behavior;   
  };  
};

int main()
{
    A objA;
    objA.DoIt();

    return 0;
}

我要做的是在实现抽象类的类中定义其行为的属性。然后我希望类BaseOfAB有一个将在子类中声明的对象。通过这样做,behavior.DoIt()应该具有在BehaviorA类中实现的行为。有谁知道怎么做这个因为我似乎无法弄明白?

提前致谢。

亲切的问候,

鲍勃

1 个答案:

答案 0 :(得分:0)

要在C ++中实现多态,您需要一个指针或对基类的引用。由于BaseOfAB将拥有此多态对象,因此您无法使用引用,但必须使用指针。最好使用智能指针,这样您就不必担心手动内存管理。接口IBehavior必须有一个虚拟析构函数,这样如果删除指向IBehavior的指针,它将正确删除派生类。

我选择std::unique_ptr因为它是C ++中最轻量级的智能指针,尽管您需要了解C ++移动语义才能使用它。

#include <iostream>
#include <memory>

class IBehavior {
public:
  virtual void DoIt() = 0;
  virtual ~IBehavior() = default;
};

class BehaviorA : public IBehavior {
public:
  void DoIt() override { std::cout << "Behavior: A\n"; }
};

class BaseOfAB {
  std::unique_ptr<IBehavior> behavior;
public:
  BaseOfAB(std::unique_ptr<IBehavior> behavior) : behavior(std::move(behavior)) {}
  void SetBehavior(std::unique_ptr<IBehavior> newBehavior) {
    behavior = std::move(newBehavior);
  }
  void DoIt() { behavior->DoIt(); };
};

class A : public BaseOfAB {
public:
  A() : BaseOfAB(std::make_unique<BehaviorA>()) {}  
};

int main() {
    A obj;
    obj.DoIt();
    obj.SetBehavior(std::make_unique<BehaviorB>());
    obj.DoIt();
}

Live demo

使用智能指针std::unique_ptr可确保在删除IBehavior实例或在BaseOfAB中替换SetBehavior实例时正确删除<Input onChangeText={(price) => this.setState({data:{...this.state.data, parseInt(price)}})} keyboardType='numeric'/> 实例。它还为复制/移动构造函数和复制/移动赋值提供了合理的默认行为。