用派生类初始化(分配)基类shared_ptr

时间:2018-12-20 22:19:57

标签: c++ polymorphism shared-ptr

我有形状类,在基类中有后缀和前缀运算符重载,它们是纯虚拟的。

class Shape
{
public:
  virtual Shape& operator ++()=0;
  virtual shared_ptr<Shape> operator++(int)=0;
  virtual void showPos()const =0;
};

class Circle : public Shape
{
public:
  virtual Shape& operator ++() override; 
  virtual shared_ptr<Shape> operator ++(int) override;
  virtual void showPos()const override;
private:
  int x=0,y=0;
};

关于前缀运算符重载没有问题。在postfix中,我需要返回一个temp变量,但无法实例化抽象基类,因此我决定使用shared_ptr作为智能指针。

void
Circle::showPos()const{ 
  cout << "X:"<< x <<", Y:"<<y <<endl;
  return;
}

Shape&
Circle::operator ++() {
  ++x;
  ++y;
  return *this;
}

shared_ptr<Shape>
Circle::operator ++(int) {
  shared_ptr<Shape> temp (Circle(*this));
  ++x;
  ++y;
  return temp;
}

int main()
{
  Circle myCircle;  

  myCircle.showPos(); //must be | X:0, Y:0
  (myCircle++)->showPos();//must be | X:0, Y:0 (now x=1,y=1)
  (myCircle++)->showPos(); //must be | X:1, Y:1 (now x=2,y=2)
  return 0;
}

实施与上述文件位于同一文件中。 错误是,

main.cpp:38:40: error: no matching function for call to
'std::shared_ptr<Shape>::shared_ptr(Circle)'
shared_ptr<Shape> temp (Circle(*this));

我应该如何使用shared_ptr?

0 个答案:

没有答案