C++无法分配抽象类型的对象

C++ Cannot allocate an object of abstract type

本文关键字:类型 对象 抽象类 抽象 分配 C++      更新时间:2023-10-16

我是C++的新手,知道这个错误是怎么回事。下面的代码。

问题:

  1. 我在另一篇文章中读到使用指向抽象基类的指针,但如果没有动态分配,我该如何做到这一点
  2. 我可以用引用代替吗?我试过了,但没有成功
  3. 我可以使用并集{Circle c,Shape s};吗;?我试过了,但没有成功

在下面的示例中,Circle和Square继承自抽象基类Shape。

int main()
{
  std::vector<Shape> shapes; //Error!
  Circle c (5);
  Square s(4);
  shapes.push_back(c);
  shapes.push_back(s);
  return 0;
}

显然,您已经将类型Shape定义为抽象类型,其中Circle和Square是从Shape派生的类型。

你通常会做的是;

std::vector<Shape*> shapes ;

并将porter存储到具有形状向量的Squares和Circles。

  shapes.push_back (&c) ;
  shapes.push_back (&s) ;

如果使用对象,则将指向这些对象的指针存储在向量中。指针只是对对象在内存中的位置的引用。当您使用关键字"new"时,内存分配器会返回一个指向已分配内存的指针。

vector<Shape*> shapes;     // EDIT: I originally some bad syntax here
Circle *c = new Circle(5); // variable c is a pointer, that points to a type Circle
Square *s = new Square(4); // variable s is a pointer, that points to a type Square
shapes.push_back(c);       // stores pointer c into array
shapes.push_back(s);       // stores pointer s into array

如果您使用的是存储在堆栈中的数据,则可以使用"&"象征

vector<Shape*> shapes;     // EDIT: I originally some bad syntax here
Circle c(5);               // Circle structure on the stack
Square s(4);               // Square structure on the stack
shapes.push_back(&c);       // stores pointer c into array
shapes.push_back(&s);       // stores pointer s into array