C++无法分配抽象类型的对象
C++ Cannot allocate an object of abstract type
我是C++的新手,知道这个错误是怎么回事。下面的代码。
问题:
- 我在另一篇文章中读到使用指向抽象基类的指针,但如果没有动态分配,我该如何做到这一点
- 我可以用引用代替吗?我试过了,但没有成功
- 我可以使用并集{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
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- C++ 多态模板类,模板类型对象的实例化
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++:初始化指向具有不同类型对象的指针数组
- 在类 C++ 中构造的模板类型对象
- 如何将颁发者名称设置为x509_req类型对象
- 将任何数据类型/对象作为参数传递以确定其大小
- 将引用类型对象的数组从C#封送到C++
- <T> 从类型对象创建类型<T1>对象的构造函数
- C++是否有现有的方法来检查对象是否是派生类型对象
- C 模板:创建与现有对象相同的类型对象
- 链接列表中的虚函数 - 多种返回类型(对象)
- 没有适当操作员()的类型对象的呼叫
- 制作垫子类型对象的数组.输出窗口显示同一帧
- 抽象类型对象的分配
- 在std::list中就地创建自定义类型对象
- 接受泛型列表类型对象的参数
- C++-将模板类型对象强制转换为特定的数据类型
- 试图在C++中打印存储在类型对象数组中的信息